3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Model\Process;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\Network;
14 * @file src/Core/Worker.php
16 * @brief Contains the class for the worker background job processing
20 * @brief Worker methods
24 private static $up_start;
25 private static $db_duration = 0;
26 private static $db_duration_count = 0;
27 private static $db_duration_write = 0;
28 private static $db_duration_stat = 0;
29 private static $lock_duration = 0;
30 private static $last_update;
33 * @brief Processes the tasks that are in the workerqueue table
35 * @param boolean $run_cron Should the cron processes be executed?
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 public static function processQueue($run_cron = true)
43 self::$up_start = microtime(true);
45 // At first check the maximum load. We shouldn't continue with a high load
46 if ($a->isMaxLoadReached()) {
47 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
51 // We now start the process. This is done after the load check since this could increase the load.
54 // Kill stale processes every 5 minutes
55 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
56 if (time() > ($last_cleanup + 300)) {
57 Config::set('system', 'worker_last_cleaned', time());
58 self::killStaleWorkers();
61 // Count active workers and compare them with a maximum value that depends on the load
62 if (self::tooMuchWorkers()) {
63 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
67 // Do we have too few memory?
68 if ($a->isMinMemoryReached()) {
69 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
73 // Possibly there are too much database connections
74 if (self::maxConnectionsReached()) {
75 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
79 // Possibly there are too much database processes that block the system
80 if ($a->isMaxProcessesReached()) {
81 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
85 // Now we start additional cron processes if we should do so
95 // We fetch the next queue entry that is about to be executed
96 while ($r = self::workerProcess($passing_slow, $entries, $deferred)) {
97 // When we are processing jobs with a lower priority, we don't refetch new jobs
98 // Otherwise fast jobs could wait behind slow ones and could be blocked.
99 $refetched = $passing_slow;
101 foreach ($r as $entry) {
102 // Assure that the priority is an integer value
103 $entry['priority'] = (int)$entry['priority'];
105 // The work will be done
106 if (!self::execute($entry)) {
107 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
111 // If possible we will fetch new jobs for this worker
113 $entries = self::totalEntries();
114 $deferred = self::deferredEntries();
115 if (Lock::acquire('worker_process', 0)) {
116 $refetched = self::findWorkerProcesses($passing_slow, $entries, $deferred);
117 Lock::release('worker_process');
122 // To avoid the quitting of multiple workers only one worker at a time will execute the check
123 if (Lock::acquire('worker', 0)) {
124 // Count active workers and compare them with a maximum value that depends on the load
125 if (self::tooMuchWorkers($entries, $deferred)) {
126 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
127 Lock::release('worker');
132 if ($a->isMinMemoryReached()) {
133 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
134 Lock::release('worker');
137 Lock::release('worker');
140 // Quit the worker once every 5 minutes
141 if (time() > ($starttime + 300)) {
142 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
147 // Cleaning up. Possibly not needed, but it doesn't harm anything.
148 if (Config::get('system', 'worker_daemon_mode', false)) {
149 self::IPCSetJobState(false);
151 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
155 * @brief Check if non executed tasks do exist in the worker queue
157 * @return boolean Returns "true" if tasks are existing
160 private static function entriesExists()
162 $stamp = (float)microtime(true);
163 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
164 self::$db_duration += (microtime(true) - $stamp);
169 * @brief Returns the number of deferred entries in the worker queue
171 * @return integer Number of deferred entries in the worker queue
174 private static function deferredEntries()
176 $stamp = (float)microtime(true);
177 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
178 self::$db_duration += (microtime(true) - $stamp);
179 self::$db_duration_count += (microtime(true) - $stamp);
184 * @brief Returns the number of non executed entries in the worker queue
186 * @return integer Number of non executed entries in the worker queue
189 private static function totalEntries()
191 $stamp = (float)microtime(true);
192 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
193 self::$db_duration += (microtime(true) - $stamp);
194 self::$db_duration_count += (microtime(true) - $stamp);
199 * @brief Returns the highest priority in the worker queue that isn't executed
201 * @return integer Number of active worker processes
204 private static function highestPriority()
206 $stamp = (float)microtime(true);
207 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
208 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
209 self::$db_duration += (microtime(true) - $stamp);
210 if (DBA::isResult($workerqueue)) {
211 return $workerqueue["priority"];
218 * @brief Returns if a process with the given priority is running
220 * @param integer $priority The priority that should be checked
222 * @return integer Is there a process running with that priority?
225 private static function processWithPriorityActive($priority)
227 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
228 return DBA::exists('workerqueue', $condition);
232 * @brief Execute a worker entry
234 * @param array $queue Workerqueue entry
236 * @return boolean "true" if further processing should be stopped
237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239 public static function execute($queue)
245 // Quit when in maintenance
246 if (Config::get('system', 'maintenance', false, true)) {
247 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
251 // Constantly check the number of parallel database processes
252 if ($a->isMaxProcessesReached()) {
253 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
257 // Constantly check the number of available database connections to let the frontend be accessible at any time
258 if (self::maxConnectionsReached()) {
259 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
263 $argv = json_decode($queue["parameter"], true);
265 // Check for existance and validity of the include file
268 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
269 // We constantly update the "executed" date every minute to avoid being killed too soon
270 if (!isset(self::$last_update)) {
271 self::$last_update = strtotime($queue["executed"]);
274 $age = (time() - self::$last_update) / 60;
275 self::$last_update = time();
278 $stamp = (float)microtime(true);
279 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
280 self::$db_duration += (microtime(true) - $stamp);
281 self::$db_duration_write += (microtime(true) - $stamp);
286 self::execFunction($queue, $include, $argv, true);
288 $stamp = (float)microtime(true);
289 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
290 if (DBA::update('workerqueue', ['done' => true], $condition)) {
291 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
293 self::$db_duration = (microtime(true) - $stamp);
294 self::$db_duration_write += (microtime(true) - $stamp);
299 // The script could be provided as full path or only with the function name
300 if ($include == basename($include)) {
301 $include = "include/".$include.".php";
304 if (!validate_include($include)) {
305 Logger::log("Include file ".$argv[0]." is not valid!");
306 $stamp = (float)microtime(true);
307 DBA::delete('workerqueue', ['id' => $queue["id"]]);
308 self::$db_duration = (microtime(true) - $stamp);
309 self::$db_duration_write += (microtime(true) - $stamp);
313 require_once $include;
315 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
317 if (function_exists($funcname)) {
318 // We constantly update the "executed" date every minute to avoid being killed too soon
319 if (!isset(self::$last_update)) {
320 self::$last_update = strtotime($queue["executed"]);
323 $age = (time() - self::$last_update) / 60;
324 self::$last_update = time();
327 $stamp = (float)microtime(true);
328 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
329 self::$db_duration += (microtime(true) - $stamp);
330 self::$db_duration_write += (microtime(true) - $stamp);
333 self::execFunction($queue, $funcname, $argv, false);
335 $stamp = (float)microtime(true);
336 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
337 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
339 self::$db_duration = (microtime(true) - $stamp);
340 self::$db_duration_write += (microtime(true) - $stamp);
342 Logger::log("Function ".$funcname." does not exist");
343 $stamp = (float)microtime(true);
344 DBA::delete('workerqueue', ['id' => $queue["id"]]);
345 self::$db_duration = (microtime(true) - $stamp);
346 self::$db_duration_write += (microtime(true) - $stamp);
353 * @brief Execute a function from the queue
355 * @param array $queue Workerqueue entry
356 * @param string $funcname name of the function
357 * @param array $argv Array of values to be passed to the function
358 * @param boolean $method_call boolean
360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
362 private static function execFunction($queue, $funcname, $argv, $method_call)
368 $argc = count($argv);
370 $new_process_id = System::processID("wrk");
372 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
374 $stamp = (float)microtime(true);
376 // We use the callstack here to analyze the performance of executed worker entries.
377 // For this reason the variables have to be initialized.
378 if (Config::get("system", "profiler")) {
379 $a->performance["start"] = microtime(true);
380 $a->performance["database"] = 0;
381 $a->performance["database_write"] = 0;
382 $a->performance["cache"] = 0;
383 $a->performance["cache_write"] = 0;
384 $a->performance["network"] = 0;
385 $a->performance["file"] = 0;
386 $a->performance["rendering"] = 0;
387 $a->performance["parser"] = 0;
388 $a->performance["marktime"] = 0;
389 $a->performance["markstart"] = microtime(true);
393 // For better logging create a new process id for every worker call
394 // But preserve the old one for the worker
395 $old_process_id = $a->process_id;
396 $a->process_id = $new_process_id;
399 $up_duration = microtime(true) - self::$up_start;
401 // Reset global data to avoid interferences
405 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
407 $funcname($argv, $argc);
410 $a->process_id = $old_process_id;
413 $duration = (microtime(true) - $stamp);
415 /* With these values we can analyze how effective the worker is.
416 * The database and rest time should be low since this is the unproductive time.
417 * The execution time is the productive time.
418 * By changing parameters like the maximum number of workers we can check the effectivness.
421 'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
422 ' - DB-Count: '.number_format(self::$db_duration_count, 4).
423 ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
424 ' - DB-Write: '.number_format(self::$db_duration_write, 4).
425 ' - Lock: '.number_format(self::$lock_duration, 4).
426 ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
427 ' - Execution: '.number_format($duration, 4),
431 self::$up_start = microtime(true);
432 self::$db_duration = 0;
433 self::$db_duration_count = 0;
434 self::$db_duration_stat = 0;
435 self::$db_duration_write = 0;
436 self::$lock_duration = 0;
438 if ($duration > 3600) {
439 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
440 } elseif ($duration > 600) {
441 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
442 } elseif ($duration > 300) {
443 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
444 } elseif ($duration > 120) {
445 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
448 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
450 // Write down the performance values into the log
451 if (Config::get("system", "profiler")) {
452 $duration = microtime(true)-$a->performance["start"];
455 if (Config::get("rendertime", "callstack")) {
456 if (isset($a->callstack["database"])) {
457 $o .= "\nDatabase Read:\n";
458 foreach ($a->callstack["database"] as $func => $time) {
459 $time = round($time, 3);
461 $o .= $func.": ".$time."\n";
465 if (isset($a->callstack["database_write"])) {
466 $o .= "\nDatabase Write:\n";
467 foreach ($a->callstack["database_write"] as $func => $time) {
468 $time = round($time, 3);
470 $o .= $func.": ".$time."\n";
474 if (isset($a->callstack["dache"])) {
475 $o .= "\nCache Read:\n";
476 foreach ($a->callstack["dache"] as $func => $time) {
477 $time = round($time, 3);
479 $o .= $func.": ".$time."\n";
483 if (isset($a->callstack["dache_write"])) {
484 $o .= "\nCache Write:\n";
485 foreach ($a->callstack["dache_write"] as $func => $time) {
486 $time = round($time, 3);
488 $o .= $func.": ".$time."\n";
492 if (isset($a->callstack["network"])) {
493 $o .= "\nNetwork:\n";
494 foreach ($a->callstack["network"] as $func => $time) {
495 $time = round($time, 3);
497 $o .= $func.": ".$time."\n";
504 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
505 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
506 number_format($a->performance["database"] - $a->performance["database_write"], 2),
507 number_format($a->performance["database_write"], 2),
508 number_format($a->performance["cache"], 2),
509 number_format($a->performance["cache_write"], 2),
510 number_format($a->performance["network"], 2),
511 number_format($a->performance["file"], 2),
512 number_format($duration - ($a->performance["database"]
513 + $a->performance["cache"] + $a->performance["cache_write"]
514 + $a->performance["network"] + $a->performance["file"]), 2),
515 number_format($duration, 2)
521 $cooldown = Config::get("system", "worker_cooldown", 0);
524 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
530 * @brief Checks if the number of database connections has reached a critical limit.
532 * @return bool Are more than 3/4 of the maximum connections used?
533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
535 private static function maxConnectionsReached()
537 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
538 $max = Config::get("system", "max_connections");
540 // Fetch the percentage level where the worker will get active
541 $maxlevel = Config::get("system", "max_connections_level", 75);
544 // the maximum number of possible user connections can be a system variable
545 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
546 if (DBA::isResult($r)) {
549 // Or it can be granted. This overrides the system variable
550 $stamp = (float)microtime(true);
551 $r = DBA::p('SHOW GRANTS');
552 self::$db_duration += (microtime(true) - $stamp);
553 while ($grants = DBA::fetch($r)) {
554 $grant = array_pop($grants);
555 if (stristr($grant, "GRANT USAGE ON")) {
556 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
564 // If $max is set we will use the processlist to determine the current number of connections
565 // The processlist only shows entries of the current user
567 $stamp = (float)microtime(true);
568 $r = DBA::p('SHOW PROCESSLIST');
569 self::$db_duration += (microtime(true) - $stamp);
570 $used = DBA::numRows($r);
573 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
575 $level = ($used / $max) * 100;
577 if ($level >= $maxlevel) {
578 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
583 // We will now check for the system values.
584 // This limit could be reached although the user limits are fine.
585 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
586 if (!DBA::isResult($r)) {
589 $max = intval($r["Value"]);
593 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
594 if (!DBA::isResult($r)) {
597 $used = intval($r["Value"]);
601 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
603 $level = $used / $max * 100;
605 if ($level < $maxlevel) {
608 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
613 * @brief fix the queue entry if the worker process died
617 private static function killStaleWorkers()
619 $stamp = (float)microtime(true);
620 $entries = DBA::select(
622 ['id', 'pid', 'executed', 'priority', 'parameter'],
623 ['NOT `done` AND `pid` != 0'],
624 ['order' => ['priority', 'created']]
626 self::$db_duration += (microtime(true) - $stamp);
628 while ($entry = DBA::fetch($entries)) {
629 if (!posix_kill($entry["pid"], 0)) {
630 $stamp = (float)microtime(true);
633 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
634 ['id' => $entry["id"]]
636 self::$db_duration += (microtime(true) - $stamp);
637 self::$db_duration_write += (microtime(true) - $stamp);
639 // Kill long running processes
640 // Check if the priority is in a valid range
641 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
642 $entry["priority"] = PRIORITY_MEDIUM;
645 // Define the maximum durations
646 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
647 $max_duration = $max_duration_defaults[$entry["priority"]];
649 $argv = json_decode($entry["parameter"], true);
650 $argv[0] = basename($argv[0]);
652 // How long is the process already running?
653 $duration = (time() - strtotime($entry["executed"])) / 60;
654 if ($duration > $max_duration) {
655 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
656 posix_kill($entry["pid"], SIGTERM);
658 // We killed the stale process.
659 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
660 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
661 $new_priority = $entry["priority"];
662 if ($entry["priority"] == PRIORITY_HIGH) {
663 $new_priority = PRIORITY_MEDIUM;
664 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
665 $new_priority = PRIORITY_LOW;
666 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
667 $new_priority = PRIORITY_NEGLIGIBLE;
669 $stamp = (float)microtime(true);
672 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
673 ['id' => $entry["id"]]
675 self::$db_duration += (microtime(true) - $stamp);
676 self::$db_duration_write += (microtime(true) - $stamp);
678 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);
685 * @brief Checks if the number of active workers exceeds the given limits
687 * @param integer $entries Total number of queue entries
688 * @param integer $deferred Number of deferred queue entries
690 * @return bool Are there too much workers running?
691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
693 public static function tooMuchWorkers($entries = 0, $deferred = 0)
695 $queues = Config::get("system", "worker_queues", 4);
697 $maxqueues = $queues;
699 $active = self::activeWorkers();
701 // Decrease the number of workers at higher load
702 $load = System::currentLoad();
704 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
706 /* Default exponent 3 causes queues to rapidly decrease as load increases.
707 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
708 * For some environments, this rapid decrease is not needed.
709 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
711 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
712 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
713 $queues = intval(ceil($slope * $maxqueues));
717 if (Config::get('system', 'worker_jpm')) {
718 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
719 $jobs_per_minute = [];
720 foreach ($intervals as $interval) {
721 if ($interval == 0) {
724 $interval = (int)$interval;
727 $stamp = (float)microtime(true);
728 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
729 self::$db_duration += (microtime(true) - $stamp);
730 self::$db_duration_stat += (microtime(true) - $stamp);
731 if ($job = DBA::fetch($jobs)) {
732 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
736 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
739 // Create a list of queue entries grouped by their priority
740 $listitem = [0 => ''];
742 $idle_workers = $active;
744 if (Config::get('system', 'worker_debug')) {
745 // Now adding all processes with workerqueue entries
746 $stamp = (float)microtime(true);
747 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
748 self::$db_duration += (microtime(true) - $stamp);
749 self::$db_duration_stat += (microtime(true) - $stamp);
750 while ($entry = DBA::fetch($jobs)) {
751 $stamp = (float)microtime(true);
752 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
753 self::$db_duration += (microtime(true) - $stamp);
754 self::$db_duration_stat += (microtime(true) - $stamp);
755 if ($process = DBA::fetch($processes)) {
756 $idle_workers -= $process["running"];
757 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
759 DBA::close($processes);
763 $stamp = (float)microtime(true);
764 $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`");
765 self::$db_duration += (microtime(true) - $stamp);
767 while ($entry = DBA::fetch($jobs)) {
768 $idle_workers -= $entry["running"];
769 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
774 $listitem[0] = "0:" . max(0, $idle_workers);
776 $processlist .= ' ('.implode(', ', $listitem).')';
778 if (empty($deferred) && empty($entries)) {
779 $deferred = self::deferredEntries();
780 $entries = max(self::totalEntries() - $deferred, 0);
783 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
784 $top_priority = self::highestPriority();
785 $high_running = self::processWithPriorityActive($top_priority);
787 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
788 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
789 $queues = $active + 1;
793 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . ($entries - $deferred) . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
795 // Are there fewer workers running as possible? Then fork a new one.
796 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
797 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
798 if (Config::get('system', 'worker_daemon_mode', false)) {
799 self::IPCSetJobState(true);
806 // if there are too much worker, we don't spawn a new one.
807 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
808 self::IPCSetJobState(false);
811 return $active > $queues;
815 * @brief Returns the number of active worker processes
817 * @return integer Number of active worker processes
820 private static function activeWorkers()
822 $stamp = (float)microtime(true);
823 $count = DBA::count('process', ['command' => 'Worker.php']);
824 self::$db_duration += (microtime(true) - $stamp);
829 * @brief Check if we should pass some slow processes
831 * When the active processes of the highest priority are using more than 2/3
832 * of all processes, we let pass slower processes.
834 * @param string $highest_priority Returns the currently highest priority
835 * @return bool We let pass a slower process than $highest_priority
838 private static function passingSlow(&$highest_priority)
840 $highest_priority = 0;
842 $stamp = (float)microtime(true);
846 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
848 self::$db_duration += (microtime(true) - $stamp);
850 // No active processes at all? Fine
851 if (!DBA::isResult($r)) {
855 while ($line = DBA::fetch($r)) {
856 $priorities[] = $line["priority"];
861 if (count($priorities) == 0) {
864 $highest_priority = min($priorities);
866 // The highest process is already the slowest one?
868 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
872 foreach ($priorities as $priority) {
873 if ($priority == $highest_priority) {
877 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
878 $passing_slow = (($high/count($priorities)) > (2/3));
881 Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
883 return $passing_slow;
887 * @brief Find and claim the next worker process for us
889 * @param boolean $passing_slow Returns if we had passed low priority processes
890 * @param integer $entries Total number of queue entries
891 * @param integer $deferred Number of deferred queue entries
892 * @return boolean Have we found something?
893 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
895 private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
899 // Check if we should pass some low priority process
900 $highest_priority = 0;
902 $passing_slow = false;
904 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
905 // We decrease the limit with the number of entries left in the queue
906 $worker_queues = Config::get("system", "worker_queues", 4);
907 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
908 $lower_job_limit = $worker_queues * $queue_length * 2;
909 $entries = max($entries - $deferred, 0);
913 $slope = $queue_length / pow($lower_job_limit, $exponent);
914 $limit = min($queue_length, ceil($slope * pow($entries, $exponent)));
916 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $entries . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
918 if (self::passingSlow($highest_priority)) {
919 // Are there waiting processes with a higher priority than the currently highest?
920 $stamp = (float)microtime(true);
921 $result = DBA::select(
924 ["`pid` = 0 AND `priority` < ? AND NOT `done` AND `next_try` < ?",
925 $highest_priority, DateTimeFormat::utcNow()],
926 ['limit' => $limit, 'order' => ['priority', 'created']]
928 self::$db_duration += (microtime(true) - $stamp);
930 while ($id = DBA::fetch($result)) {
935 $found = (count($ids) > 0);
938 // Give slower processes some processing time
939 $stamp = (float)microtime(true);
940 $result = DBA::select(
943 ["`pid` = 0 AND `priority` > ? AND NOT `done` AND `next_try` < ?",
944 $highest_priority, DateTimeFormat::utcNow()],
945 ['limit' => $limit, 'order' => ['priority', 'created']]
947 self::$db_duration += (microtime(true) - $stamp);
949 while ($id = DBA::fetch($result)) {
954 $found = (count($ids) > 0);
955 $passing_slow = $found;
959 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
961 $stamp = (float)microtime(true);
962 $result = DBA::select(
965 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
966 DateTimeFormat::utcNow()],
967 ['limit' => $limit, 'order' => ['priority', 'created']]
969 self::$db_duration += (microtime(true) - $stamp);
971 while ($id = DBA::fetch($result)) {
976 $found = (count($ids) > 0);
980 $stamp = (float)microtime(true);
981 $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
982 array_unshift($ids, $condition);
983 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
984 self::$db_duration += (microtime(true) - $stamp);
985 self::$db_duration_write += (microtime(true) - $stamp);
992 * @brief Returns the next worker process
994 * @param boolean $passing_slow Returns if we had passed low priority processes
995 * @param integer $entries Returns total number of queue entries
996 * @param integer $deferred Returns number of deferred queue entries
998 * @return string SQL statement
999 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1001 public static function workerProcess(&$passing_slow, &$entries, &$deferred)
1003 // There can already be jobs for us in the queue.
1004 $stamp = (float)microtime(true);
1005 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1006 self::$db_duration += (microtime(true) - $stamp);
1007 if (DBA::isResult($r)) {
1008 return DBA::toArray($r);
1012 // Counting the rows outside the lock reduces the lock time
1013 $entries = self::totalEntries();
1014 $deferred = self::deferredEntries();
1016 $stamp = (float)microtime(true);
1017 if (!Lock::acquire('worker_process')) {
1020 self::$lock_duration += (microtime(true) - $stamp);
1022 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
1024 Lock::release('worker_process');
1027 $stamp = (float)microtime(true);
1028 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1029 self::$db_duration += (microtime(true) - $stamp);
1030 return DBA::toArray($r);
1036 * @brief Removes a workerqueue entry from the current process
1038 * @throws \Exception
1040 public static function unclaimProcess()
1042 $mypid = getmypid();
1044 $stamp = (float)microtime(true);
1045 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1046 self::$db_duration += (microtime(true) - $stamp);
1047 self::$db_duration_write += (microtime(true) - $stamp);
1051 * @brief Call the front end worker
1053 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1055 public static function callWorker()
1057 if (!Config::get("system", "frontend_worker")) {
1061 $url = System::baseUrl()."/worker";
1062 Network::fetchUrl($url, false, $redirects, 1);
1066 * @brief Call the front end worker if there aren't any active
1068 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1070 public static function executeIfIdle()
1072 if (!Config::get("system", "frontend_worker")) {
1076 // Do we have "proc_open"? Then we can fork the worker
1077 if (function_exists("proc_open")) {
1078 // When was the last time that we called the worker?
1079 // Less than one minute? Then we quit
1080 if ((time() - Config::get("system", "worker_started")) < 60) {
1084 Config::set("system", "worker_started", time());
1086 // Do we have enough running workers? Then we quit here.
1087 if (self::tooMuchWorkers()) {
1088 // Cleaning dead processes
1089 self::killStaleWorkers();
1090 Process::deleteInactive();
1097 Logger::log('Call worker', Logger::DEBUG);
1098 self::spawnWorker();
1102 // We cannot execute background processes.
1103 // We now run the processes from the frontend.
1104 // This won't work with long running processes.
1107 self::clearProcesses();
1109 $workers = self::activeWorkers();
1111 if ($workers == 0) {
1117 * @brief Removes long running worker processes
1119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1121 public static function clearProcesses()
1123 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1125 /// @todo We should clean up the corresponding workerqueue entries as well
1126 $stamp = (float)microtime(true);
1127 $condition = ["`created` < ? AND `command` = 'worker.php'",
1128 DateTimeFormat::utc("now - ".$timeout." minutes")];
1129 DBA::delete('process', $condition);
1130 self::$db_duration = (microtime(true) - $stamp);
1131 self::$db_duration_write += (microtime(true) - $stamp);
1135 * @brief Runs the cron processes
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139 private static function runCron()
1141 Logger::log('Add cron entries', Logger::DEBUG);
1143 // Check for spooled items
1144 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1146 // Run the cron job that calls all other jobs
1147 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1149 // Cleaning dead processes
1150 self::killStaleWorkers();
1154 * @brief Spawns a new worker
1155 * @param bool $do_cron
1157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1159 public static function spawnWorker($do_cron = false)
1161 $command = 'bin/worker.php';
1163 $args = ['no_cron' => !$do_cron];
1165 get_app()->proc_run($command, $args);
1167 // after spawning we have to remove the flag.
1168 if (Config::get('system', 'worker_daemon_mode', false)) {
1169 self::IPCSetJobState(false);
1174 * @brief Adds tasks to the worker queue
1176 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1178 * next args are passed as $cmd command line
1179 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1180 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1182 * @return boolean "false" if proc_run couldn't be executed
1183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1184 * @note $cmd and string args are surrounded with ""
1190 public static function add($cmd)
1192 $args = func_get_args();
1194 if (!count($args)) {
1198 $arr = ['args' => $args, 'run_cmd' => true];
1200 Hook::callAll("proc_run", $arr);
1201 if (!$arr['run_cmd'] || !count($args)) {
1205 $priority = PRIORITY_MEDIUM;
1206 $dont_fork = Config::get("system", "worker_dont_fork", false);
1207 $created = DateTimeFormat::utcNow();
1208 $force_priority = false;
1210 $run_parameter = array_shift($args);
1212 if (is_int($run_parameter)) {
1213 $priority = $run_parameter;
1214 } elseif (is_array($run_parameter)) {
1215 if (isset($run_parameter['priority'])) {
1216 $priority = $run_parameter['priority'];
1218 if (isset($run_parameter['created'])) {
1219 $created = $run_parameter['created'];
1221 if (isset($run_parameter['dont_fork'])) {
1222 $dont_fork = $run_parameter['dont_fork'];
1224 if (isset($run_parameter['force_priority'])) {
1225 $force_priority = $run_parameter['force_priority'];
1229 $parameters = json_encode($args);
1230 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1232 // Quit if there was a database error - a precaution for the update process to 3.5.3
1233 if (DBA::errorNo() != 0) {
1238 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1239 } elseif ($force_priority) {
1240 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1243 // Should we quit and wait for the worker to be called as a cronjob?
1248 // If there is a lock then we don't have to check for too much worker
1249 if (!Lock::acquire('worker', 0)) {
1253 // If there are already enough workers running, don't fork another one
1254 $quit = self::tooMuchWorkers();
1255 Lock::release('worker');
1261 // We tell the daemon that a new job entry exists
1262 if (Config::get('system', 'worker_daemon_mode', false)) {
1263 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1267 // Now call the worker to execute the jobs that we just added to the queue
1268 self::spawnWorker();
1274 * Defers the current worker entry
1276 public static function defer()
1278 if (empty(BaseObject::getApp()->queue)) {
1282 $queue = BaseObject::getApp()->queue;
1284 $retrial = $queue['retrial'];
1286 $priority = $queue['priority'];
1288 if ($retrial > 14) {
1289 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1293 // Calculate the delay until the next trial
1294 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1295 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1297 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1298 $priority = PRIORITY_MEDIUM;
1299 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1300 $priority = PRIORITY_LOW;
1301 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1302 $priority = PRIORITY_NEGLIGIBLE;
1305 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1307 $stamp = (float)microtime(true);
1308 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1309 DBA::update('workerqueue', $fields, ['id' => $id]);
1310 self::$db_duration += (microtime(true) - $stamp);
1311 self::$db_duration_write += (microtime(true) - $stamp);
1315 * Log active processes into the "process" table
1317 * @brief Log active processes into the "process" table
1319 public static function startProcess()
1321 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1323 $command = basename($trace[0]['file']);
1325 Process::deleteInactive();
1327 Process::insert($command);
1331 * Remove the active process from the "process" table
1333 * @brief Remove the active process from the "process" table
1335 * @throws \Exception
1337 public static function endProcess()
1339 return Process::deleteByPid();
1343 * Set the flag if some job is waiting
1345 * @brief Set the flag if some job is waiting
1346 * @param boolean $jobs Is there a waiting job?
1347 * @throws \Exception
1349 public static function IPCSetJobState($jobs)
1351 $stamp = (float)microtime(true);
1352 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1353 self::$db_duration += (microtime(true) - $stamp);
1354 self::$db_duration_write += (microtime(true) - $stamp);
1358 * Checks if some worker job waits to be executed
1360 * @brief Checks if some worker job waits to be executed
1362 * @throws \Exception
1364 public static function IPCJobsExists()
1366 $stamp = (float)microtime(true);
1367 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1368 self::$db_duration += (microtime(true) - $stamp);
1370 // When we don't have a row, no job is running
1371 if (!DBA::isResult($row)) {
1375 return (bool)$row['jobs'];