3 * @file src/Core/Worker.php
5 namespace Friendica\Core;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Model\Process;
10 use Friendica\Util\DateTimeFormat;
11 use Friendica\Util\Network;
14 * @file src/Core/Worker.php
16 * @brief Contains the class for the worker background job processing
20 * @brief Worker methods
24 private static $up_start;
25 private static $db_duration = 0;
26 private static $db_duration_count = 0;
27 private static $db_duration_write = 0;
28 private static $db_duration_stat = 0;
29 private static $lock_duration = 0;
30 private static $last_update;
33 * @brief Processes the tasks that are in the workerqueue table
35 * @param boolean $run_cron Should the cron processes be executed?
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 public static function processQueue($run_cron = true)
43 // Ensure that all "strtotime" operations do run timezone independent
44 date_default_timezone_set('UTC');
46 self::$up_start = microtime(true);
48 // At first check the maximum load. We shouldn't continue with a high load
49 if ($a->isMaxLoadReached()) {
50 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
54 // We now start the process. This is done after the load check since this could increase the load.
57 // Kill stale processes every 5 minutes
58 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
59 if (time() > ($last_cleanup + 300)) {
60 Config::set('system', 'worker_last_cleaned', time());
61 self::killStaleWorkers();
64 // Count active workers and compare them with a maximum value that depends on the load
65 if (self::tooMuchWorkers()) {
66 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
70 // Do we have too few memory?
71 if ($a->isMinMemoryReached()) {
72 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
76 // Possibly there are too much database connections
77 if (self::maxConnectionsReached()) {
78 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
82 // Possibly there are too much database processes that block the system
83 if ($a->isMaxProcessesReached()) {
84 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
88 // Now we start additional cron processes if we should do so
95 // We fetch the next queue entry that is about to be executed
96 while ($r = self::workerProcess()) {
97 foreach ($r as $entry) {
98 // Assure that the priority is an integer value
99 $entry['priority'] = (int)$entry['priority'];
101 // The work will be done
102 if (!self::execute($entry)) {
103 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
107 // If possible we will fetch new jobs for this worker
108 if (!self::getWaitingJobForPID() && Lock::acquire('worker_process', 0)) {
109 self::findWorkerProcesses();
110 Lock::release('worker_process');
114 // To avoid the quitting of multiple workers only one worker at a time will execute the check
115 if (Lock::acquire('worker', 0)) {
116 // Count active workers and compare them with a maximum value that depends on the load
117 if (self::tooMuchWorkers()) {
118 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
119 Lock::release('worker');
124 if ($a->isMinMemoryReached()) {
125 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
126 Lock::release('worker');
129 Lock::release('worker');
132 // Quit the worker once every 5 minutes
133 if (time() > ($starttime + 300)) {
134 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
139 // Cleaning up. Possibly not needed, but it doesn't harm anything.
140 if (Config::get('system', 'worker_daemon_mode', false)) {
141 self::IPCSetJobState(false);
143 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
147 * @brief Check if non executed tasks do exist in the worker queue
149 * @return boolean Returns "true" if tasks are existing
152 private static function entriesExists()
154 $stamp = (float)microtime(true);
155 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
156 self::$db_duration += (microtime(true) - $stamp);
161 * @brief Returns the number of deferred entries in the worker queue
163 * @return integer Number of deferred entries in the worker queue
166 private static function deferredEntries()
168 $stamp = (float)microtime(true);
169 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
170 self::$db_duration += (microtime(true) - $stamp);
171 self::$db_duration_count += (microtime(true) - $stamp);
176 * @brief Returns the number of non executed entries in the worker queue
178 * @return integer Number of non executed entries in the worker queue
181 private static function totalEntries()
183 $stamp = (float)microtime(true);
184 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
185 self::$db_duration += (microtime(true) - $stamp);
186 self::$db_duration_count += (microtime(true) - $stamp);
191 * @brief Returns the highest priority in the worker queue that isn't executed
193 * @return integer Number of active worker processes
196 private static function highestPriority()
198 $stamp = (float)microtime(true);
199 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
200 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
201 self::$db_duration += (microtime(true) - $stamp);
202 if (DBA::isResult($workerqueue)) {
203 return $workerqueue["priority"];
210 * @brief Returns if a process with the given priority is running
212 * @param integer $priority The priority that should be checked
214 * @return integer Is there a process running with that priority?
217 private static function processWithPriorityActive($priority)
219 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
220 return DBA::exists('workerqueue', $condition);
224 * @brief Execute a worker entry
226 * @param array $queue Workerqueue entry
228 * @return boolean "true" if further processing should be stopped
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 public static function execute($queue)
237 // Quit when in maintenance
238 if (Config::get('system', 'maintenance', false, true)) {
239 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
243 // Constantly check the number of parallel database processes
244 if ($a->isMaxProcessesReached()) {
245 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
249 // Constantly check the number of available database connections to let the frontend be accessible at any time
250 if (self::maxConnectionsReached()) {
251 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
255 $argv = json_decode($queue["parameter"], true);
257 // Check for existance and validity of the include file
260 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
261 // We constantly update the "executed" date every minute to avoid being killed too soon
262 if (!isset(self::$last_update)) {
263 self::$last_update = strtotime($queue["executed"]);
266 $age = (time() - self::$last_update) / 60;
267 self::$last_update = time();
270 $stamp = (float)microtime(true);
271 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
272 self::$db_duration += (microtime(true) - $stamp);
273 self::$db_duration_write += (microtime(true) - $stamp);
278 self::execFunction($queue, $include, $argv, true);
280 $stamp = (float)microtime(true);
281 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
282 if (DBA::update('workerqueue', ['done' => true], $condition)) {
283 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
285 self::$db_duration = (microtime(true) - $stamp);
286 self::$db_duration_write += (microtime(true) - $stamp);
291 // The script could be provided as full path or only with the function name
292 if ($include == basename($include)) {
293 $include = "include/".$include.".php";
296 if (!validate_include($include)) {
297 Logger::log("Include file ".$argv[0]." is not valid!");
298 $stamp = (float)microtime(true);
299 DBA::delete('workerqueue', ['id' => $queue["id"]]);
300 self::$db_duration = (microtime(true) - $stamp);
301 self::$db_duration_write += (microtime(true) - $stamp);
305 require_once $include;
307 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
309 if (function_exists($funcname)) {
310 // We constantly update the "executed" date every minute to avoid being killed too soon
311 if (!isset(self::$last_update)) {
312 self::$last_update = strtotime($queue["executed"]);
315 $age = (time() - self::$last_update) / 60;
316 self::$last_update = time();
319 $stamp = (float)microtime(true);
320 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
321 self::$db_duration += (microtime(true) - $stamp);
322 self::$db_duration_write += (microtime(true) - $stamp);
325 self::execFunction($queue, $funcname, $argv, false);
327 $stamp = (float)microtime(true);
328 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
329 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
331 self::$db_duration = (microtime(true) - $stamp);
332 self::$db_duration_write += (microtime(true) - $stamp);
334 Logger::log("Function ".$funcname." does not exist");
335 $stamp = (float)microtime(true);
336 DBA::delete('workerqueue', ['id' => $queue["id"]]);
337 self::$db_duration = (microtime(true) - $stamp);
338 self::$db_duration_write += (microtime(true) - $stamp);
345 * @brief Execute a function from the queue
347 * @param array $queue Workerqueue entry
348 * @param string $funcname name of the function
349 * @param array $argv Array of values to be passed to the function
350 * @param boolean $method_call boolean
352 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
354 private static function execFunction($queue, $funcname, $argv, $method_call)
360 $argc = count($argv);
362 // Currently deactivated, since the new logger doesn't support this
363 //$new_process_id = System::processID("wrk");
364 $new_process_id = '';
366 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
368 $stamp = (float)microtime(true);
370 // We use the callstack here to analyze the performance of executed worker entries.
371 // For this reason the variables have to be initialized.
372 if (Config::get("system", "profiler")) {
373 $a->performance["start"] = microtime(true);
374 $a->performance["database"] = 0;
375 $a->performance["database_write"] = 0;
376 $a->performance["cache"] = 0;
377 $a->performance["cache_write"] = 0;
378 $a->performance["network"] = 0;
379 $a->performance["file"] = 0;
380 $a->performance["rendering"] = 0;
381 $a->performance["parser"] = 0;
382 $a->performance["marktime"] = 0;
383 $a->performance["markstart"] = microtime(true);
387 // For better logging create a new process id for every worker call
388 // But preserve the old one for the worker
389 $old_process_id = $a->process_id;
390 $a->process_id = $new_process_id;
393 $up_duration = microtime(true) - self::$up_start;
395 // Reset global data to avoid interferences
399 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
401 $funcname($argv, $argc);
404 $a->process_id = $old_process_id;
407 $duration = (microtime(true) - $stamp);
409 /* With these values we can analyze how effective the worker is.
410 * The database and rest time should be low since this is the unproductive time.
411 * The execution time is the productive time.
412 * By changing parameters like the maximum number of workers we can check the effectivness.
415 'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
416 ' - DB-Count: '.number_format(self::$db_duration_count, 4).
417 ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
418 ' - DB-Write: '.number_format(self::$db_duration_write, 4).
419 ' - Lock: '.number_format(self::$lock_duration, 4).
420 ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
421 ' - Execution: '.number_format($duration, 4),
425 self::$up_start = microtime(true);
426 self::$db_duration = 0;
427 self::$db_duration_count = 0;
428 self::$db_duration_stat = 0;
429 self::$db_duration_write = 0;
430 self::$lock_duration = 0;
432 if ($duration > 3600) {
433 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
434 } elseif ($duration > 600) {
435 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
436 } elseif ($duration > 300) {
437 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
438 } elseif ($duration > 120) {
439 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
442 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".number_format($duration, 4)." seconds. Process PID: ".$new_process_id);
444 // Write down the performance values into the log
445 if (Config::get("system", "profiler")) {
446 $duration = microtime(true)-$a->performance["start"];
449 if (Config::get("rendertime", "callstack")) {
450 if (isset($a->callstack["database"])) {
451 $o .= "\nDatabase Read:\n";
452 foreach ($a->callstack["database"] as $func => $time) {
453 $time = round($time, 3);
455 $o .= $func.": ".$time."\n";
459 if (isset($a->callstack["database_write"])) {
460 $o .= "\nDatabase Write:\n";
461 foreach ($a->callstack["database_write"] as $func => $time) {
462 $time = round($time, 3);
464 $o .= $func.": ".$time."\n";
468 if (isset($a->callstack["dache"])) {
469 $o .= "\nCache Read:\n";
470 foreach ($a->callstack["dache"] as $func => $time) {
471 $time = round($time, 3);
473 $o .= $func.": ".$time."\n";
477 if (isset($a->callstack["dache_write"])) {
478 $o .= "\nCache Write:\n";
479 foreach ($a->callstack["dache_write"] as $func => $time) {
480 $time = round($time, 3);
482 $o .= $func.": ".$time."\n";
486 if (isset($a->callstack["network"])) {
487 $o .= "\nNetwork:\n";
488 foreach ($a->callstack["network"] as $func => $time) {
489 $time = round($time, 3);
491 $o .= $func.": ".$time."\n";
498 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
499 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
500 number_format($a->performance["database"] - $a->performance["database_write"], 2),
501 number_format($a->performance["database_write"], 2),
502 number_format($a->performance["cache"], 2),
503 number_format($a->performance["cache_write"], 2),
504 number_format($a->performance["network"], 2),
505 number_format($a->performance["file"], 2),
506 number_format($duration - ($a->performance["database"]
507 + $a->performance["cache"] + $a->performance["cache_write"]
508 + $a->performance["network"] + $a->performance["file"]), 2),
509 number_format($duration, 2)
515 $cooldown = Config::get("system", "worker_cooldown", 0);
518 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
524 * @brief Checks if the number of database connections has reached a critical limit.
526 * @return bool Are more than 3/4 of the maximum connections used?
527 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 private static function maxConnectionsReached()
531 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
532 $max = Config::get("system", "max_connections");
534 // Fetch the percentage level where the worker will get active
535 $maxlevel = Config::get("system", "max_connections_level", 75);
538 // the maximum number of possible user connections can be a system variable
539 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
540 if (DBA::isResult($r)) {
543 // Or it can be granted. This overrides the system variable
544 $stamp = (float)microtime(true);
545 $r = DBA::p('SHOW GRANTS');
546 self::$db_duration += (microtime(true) - $stamp);
547 while ($grants = DBA::fetch($r)) {
548 $grant = array_pop($grants);
549 if (stristr($grant, "GRANT USAGE ON")) {
550 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
558 // If $max is set we will use the processlist to determine the current number of connections
559 // The processlist only shows entries of the current user
561 $stamp = (float)microtime(true);
562 $r = DBA::p('SHOW PROCESSLIST');
563 self::$db_duration += (microtime(true) - $stamp);
564 $used = DBA::numRows($r);
567 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
569 $level = ($used / $max) * 100;
571 if ($level >= $maxlevel) {
572 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
577 // We will now check for the system values.
578 // This limit could be reached although the user limits are fine.
579 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
580 if (!DBA::isResult($r)) {
583 $max = intval($r["Value"]);
587 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
588 if (!DBA::isResult($r)) {
591 $used = intval($r["Value"]);
595 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
597 $level = $used / $max * 100;
599 if ($level < $maxlevel) {
602 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
607 * @brief fix the queue entry if the worker process died
611 private static function killStaleWorkers()
613 $stamp = (float)microtime(true);
614 $entries = DBA::select(
616 ['id', 'pid', 'executed', 'priority', 'parameter'],
617 ['NOT `done` AND `pid` != 0'],
618 ['order' => ['priority', 'created']]
620 self::$db_duration += (microtime(true) - $stamp);
622 while ($entry = DBA::fetch($entries)) {
623 if (!posix_kill($entry["pid"], 0)) {
624 $stamp = (float)microtime(true);
627 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
628 ['id' => $entry["id"]]
630 self::$db_duration += (microtime(true) - $stamp);
631 self::$db_duration_write += (microtime(true) - $stamp);
633 // Kill long running processes
634 // Check if the priority is in a valid range
635 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
636 $entry["priority"] = PRIORITY_MEDIUM;
639 // Define the maximum durations
640 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
641 $max_duration = $max_duration_defaults[$entry["priority"]];
643 $argv = json_decode($entry["parameter"], true);
644 $argv[0] = basename($argv[0]);
646 // How long is the process already running?
647 $duration = (time() - strtotime($entry["executed"])) / 60;
648 if ($duration > $max_duration) {
649 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
650 posix_kill($entry["pid"], SIGTERM);
652 // We killed the stale process.
653 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
654 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
655 $new_priority = $entry["priority"];
656 if ($entry["priority"] == PRIORITY_HIGH) {
657 $new_priority = PRIORITY_MEDIUM;
658 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
659 $new_priority = PRIORITY_LOW;
660 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
661 $new_priority = PRIORITY_NEGLIGIBLE;
663 $stamp = (float)microtime(true);
666 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
667 ['id' => $entry["id"]]
669 self::$db_duration += (microtime(true) - $stamp);
670 self::$db_duration_write += (microtime(true) - $stamp);
672 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);
679 * @brief Checks if the number of active workers exceeds the given limits
681 * @return bool Are there too much workers running?
682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 private static function tooMuchWorkers()
686 $queues = Config::get("system", "worker_queues", 4);
688 $maxqueues = $queues;
690 $active = self::activeWorkers();
692 // Decrease the number of workers at higher load
693 $load = System::currentLoad();
695 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
697 /* Default exponent 3 causes queues to rapidly decrease as load increases.
698 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
699 * For some environments, this rapid decrease is not needed.
700 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
702 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
703 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
704 $queues = intval(ceil($slope * $maxqueues));
708 if (Config::get('system', 'worker_jpm')) {
709 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
710 $jobs_per_minute = [];
711 foreach ($intervals as $interval) {
712 if ($interval == 0) {
715 $interval = (int)$interval;
718 $stamp = (float)microtime(true);
719 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
720 self::$db_duration += (microtime(true) - $stamp);
721 self::$db_duration_stat += (microtime(true) - $stamp);
722 if ($job = DBA::fetch($jobs)) {
723 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
727 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
730 // Create a list of queue entries grouped by their priority
731 $listitem = [0 => ''];
733 $idle_workers = $active;
735 $deferred = self::deferredEntries();
737 if (Config::get('system', 'worker_debug')) {
738 $waiting_processes = 0;
739 // Now adding all processes with workerqueue entries
740 $stamp = (float)microtime(true);
741 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
742 self::$db_duration += (microtime(true) - $stamp);
743 self::$db_duration_stat += (microtime(true) - $stamp);
744 while ($entry = DBA::fetch($jobs)) {
745 $stamp = (float)microtime(true);
746 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
747 self::$db_duration += (microtime(true) - $stamp);
748 self::$db_duration_stat += (microtime(true) - $stamp);
749 if ($process = DBA::fetch($processes)) {
750 $idle_workers -= $process["running"];
751 $waiting_processes += $entry["entries"];
752 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
754 DBA::close($processes);
757 $entries = $deferred + $waiting_processes;
759 $entries = self::totalEntries();
760 $waiting_processes = max(0, $entries - $deferred);
761 $stamp = (float)microtime(true);
762 $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`");
763 self::$db_duration += (microtime(true) - $stamp);
764 self::$db_duration_stat += (microtime(true) - $stamp);
766 while ($entry = DBA::fetch($jobs)) {
767 $idle_workers -= $entry["running"];
768 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
773 $listitem[0] = "0:" . max(0, $idle_workers);
775 $processlist .= ' ('.implode(', ', $listitem).')';
777 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
778 $top_priority = self::highestPriority();
779 $high_running = self::processWithPriorityActive($top_priority);
781 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
782 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
783 $queues = $active + 1;
787 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
789 // Are there fewer workers running as possible? Then fork a new one.
790 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
791 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
792 if (Config::get('system', 'worker_daemon_mode', false)) {
793 self::IPCSetJobState(true);
800 // if there are too much worker, we don't spawn a new one.
801 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
802 self::IPCSetJobState(false);
805 return $active > $queues;
809 * @brief Returns the number of active worker processes
811 * @return integer Number of active worker processes
814 private static function activeWorkers()
816 $stamp = (float)microtime(true);
817 $count = DBA::count('process', ['command' => 'Worker.php']);
818 self::$db_duration += (microtime(true) - $stamp);
823 * @brief Returns waiting jobs for the current process id
825 * @return array waiting workerqueue jobs
828 private static function getWaitingJobForPID()
830 $stamp = (float)microtime(true);
831 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
832 self::$db_duration += (microtime(true) - $stamp);
833 if (DBA::isResult($r)) {
834 return DBA::toArray($r);
842 * @brief Returns the next jobs that should be executed
844 * @return array array with next jobs
847 private static function nextProcess()
849 $priority = self::nextPriority();
850 if (empty($priority)) {
851 Logger::log('No tasks found', Logger::DEBUG);
855 if ($priority <= PRIORITY_MEDIUM) {
856 $limit = Config::get('system', 'worker_fetch_limit', 1);
862 $stamp = (float)microtime(true);
863 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
864 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
865 self::$db_duration += (microtime(true) - $stamp);
866 while ($task = DBA::fetch($tasks)) {
867 $ids[] = $task['id'];
871 Logger::log('Found task(s) ' . implode(', ', $ids) . ' with priority ' .$priority, Logger::DEBUG);
876 * @brief Returns the priority of the next workerqueue job
878 * @return string priority
881 private static function nextPriority()
884 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
885 foreach ($priorities as $priority) {
886 $stamp = (float)microtime(true);
887 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
888 $waiting[$priority] = true;
890 self::$db_duration += (microtime(true) - $stamp);
893 if (!empty($waiting[PRIORITY_CRITICAL])) {
894 return PRIORITY_CRITICAL;
899 $stamp = (float)microtime(true);
900 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
901 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
902 WHERE NOT `done` GROUP BY `priority`");
903 self::$db_duration += (microtime(true) - $stamp);
904 while ($process = DBA::fetch($processes)) {
905 $running[$process['priority']] = $process['running'];
906 $running_total += $process['running'];
908 DBA::close($processes);
910 foreach ($priorities as $priority) {
911 if (!empty($waiting[$priority]) && empty($running[$priority])) {
912 Logger::log('No running worker found with priority ' . $priority . ' - assigning it.', Logger::DEBUG);
917 $active = max(self::activeWorkers(), $running_total);
918 $priorities = max(count($waiting), count($running));
922 for ($i = 1; $i <= $priorities; ++$i) {
923 $total += pow($i, $exponent);
927 for ($i = 1; $i <= $priorities; ++$i) {
928 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
932 foreach ($running as $priority => $workers) {
933 if ($workers < $limit[$i++]) {
934 Logger::log('Priority ' . $priority . ' has got ' . $workers . ' workers out of a limit of ' . $limit[$i - 1], Logger::DEBUG);
939 if (!empty($waiting)) {
940 $priority = array_shift(array_keys($waiting));
941 Logger::log('No underassigned priority found, now taking the highest priority (' . $priority . ').', Logger::DEBUG);
949 * @brief Find and claim the next worker process for us
951 * @return boolean Have we found something?
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 private static function findWorkerProcesses()
958 $ids = self::nextProcess();
960 // If there is no result we check without priority limit
962 $stamp = (float)microtime(true);
963 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
964 $result = DBA::select('workerqueue', ['id'], $condition, ['limit' => 1, 'order' => ['priority', 'created']]);
965 self::$db_duration += (microtime(true) - $stamp);
967 while ($id = DBA::fetch($result)) {
974 $stamp = (float)microtime(true);
975 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
976 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
977 self::$db_duration += (microtime(true) - $stamp);
978 self::$db_duration_write += (microtime(true) - $stamp);
985 * @brief Returns the next worker process
987 * @return string SQL statement
988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
990 public static function workerProcess()
992 // There can already be jobs for us in the queue.
993 $waiting = self::getWaitingJobForPID();
994 if (!empty($waiting)) {
998 $stamp = (float)microtime(true);
999 if (!Lock::acquire('worker_process')) {
1002 self::$lock_duration += (microtime(true) - $stamp);
1004 $found = self::findWorkerProcesses();
1006 Lock::release('worker_process');
1009 $stamp = (float)microtime(true);
1010 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1011 self::$db_duration += (microtime(true) - $stamp);
1012 return DBA::toArray($r);
1018 * @brief Removes a workerqueue entry from the current process
1020 * @throws \Exception
1022 public static function unclaimProcess()
1024 $mypid = getmypid();
1026 $stamp = (float)microtime(true);
1027 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1028 self::$db_duration += (microtime(true) - $stamp);
1029 self::$db_duration_write += (microtime(true) - $stamp);
1033 * @brief Call the front end worker
1035 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1037 public static function callWorker()
1039 if (!Config::get("system", "frontend_worker")) {
1043 $url = System::baseUrl()."/worker";
1044 Network::fetchUrl($url, false, $redirects, 1);
1048 * @brief Call the front end worker if there aren't any active
1050 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1052 public static function executeIfIdle()
1054 if (!Config::get("system", "frontend_worker")) {
1058 // Do we have "proc_open"? Then we can fork the worker
1059 if (function_exists("proc_open")) {
1060 // When was the last time that we called the worker?
1061 // Less than one minute? Then we quit
1062 if ((time() - Config::get("system", "worker_started")) < 60) {
1066 Config::set("system", "worker_started", time());
1068 // Do we have enough running workers? Then we quit here.
1069 if (self::tooMuchWorkers()) {
1070 // Cleaning dead processes
1071 self::killStaleWorkers();
1072 Process::deleteInactive();
1079 Logger::log('Call worker', Logger::DEBUG);
1080 self::spawnWorker();
1084 // We cannot execute background processes.
1085 // We now run the processes from the frontend.
1086 // This won't work with long running processes.
1089 self::clearProcesses();
1091 $workers = self::activeWorkers();
1093 if ($workers == 0) {
1099 * @brief Removes long running worker processes
1101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1103 public static function clearProcesses()
1105 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1107 /// @todo We should clean up the corresponding workerqueue entries as well
1108 $stamp = (float)microtime(true);
1109 $condition = ["`created` < ? AND `command` = 'worker.php'",
1110 DateTimeFormat::utc("now - ".$timeout." minutes")];
1111 DBA::delete('process', $condition);
1112 self::$db_duration = (microtime(true) - $stamp);
1113 self::$db_duration_write += (microtime(true) - $stamp);
1117 * @brief Runs the cron processes
1119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1121 private static function runCron()
1123 Logger::log('Add cron entries', Logger::DEBUG);
1125 // Check for spooled items
1126 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1128 // Run the cron job that calls all other jobs
1129 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1131 // Cleaning dead processes
1132 self::killStaleWorkers();
1136 * @brief Spawns a new worker
1137 * @param bool $do_cron
1139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1141 public static function spawnWorker($do_cron = false)
1143 $command = 'bin/worker.php';
1145 $args = ['no_cron' => !$do_cron];
1147 get_app()->proc_run($command, $args);
1149 // after spawning we have to remove the flag.
1150 if (Config::get('system', 'worker_daemon_mode', false)) {
1151 self::IPCSetJobState(false);
1156 * @brief Adds tasks to the worker queue
1158 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1160 * next args are passed as $cmd command line
1161 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1162 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1164 * @return boolean "false" if proc_run couldn't be executed
1165 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1166 * @note $cmd and string args are surrounded with ""
1172 public static function add($cmd)
1174 $args = func_get_args();
1176 if (!count($args)) {
1180 $arr = ['args' => $args, 'run_cmd' => true];
1182 Hook::callAll("proc_run", $arr);
1183 if (!$arr['run_cmd'] || !count($args)) {
1187 $priority = PRIORITY_MEDIUM;
1188 $dont_fork = Config::get("system", "worker_dont_fork", false);
1189 $created = DateTimeFormat::utcNow();
1190 $force_priority = false;
1192 $run_parameter = array_shift($args);
1194 if (is_int($run_parameter)) {
1195 $priority = $run_parameter;
1196 } elseif (is_array($run_parameter)) {
1197 if (isset($run_parameter['priority'])) {
1198 $priority = $run_parameter['priority'];
1200 if (isset($run_parameter['created'])) {
1201 $created = $run_parameter['created'];
1203 if (isset($run_parameter['dont_fork'])) {
1204 $dont_fork = $run_parameter['dont_fork'];
1206 if (isset($run_parameter['force_priority'])) {
1207 $force_priority = $run_parameter['force_priority'];
1211 $parameters = json_encode($args);
1212 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1214 // Quit if there was a database error - a precaution for the update process to 3.5.3
1215 if (DBA::errorNo() != 0) {
1220 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1221 } elseif ($force_priority) {
1222 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1225 // Should we quit and wait for the worker to be called as a cronjob?
1230 // If there is a lock then we don't have to check for too much worker
1231 if (!Lock::acquire('worker', 0)) {
1235 // If there are already enough workers running, don't fork another one
1236 $quit = self::tooMuchWorkers();
1237 Lock::release('worker');
1243 // We tell the daemon that a new job entry exists
1244 if (Config::get('system', 'worker_daemon_mode', false)) {
1245 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1249 // Now call the worker to execute the jobs that we just added to the queue
1250 self::spawnWorker();
1256 * Defers the current worker entry
1258 public static function defer()
1260 if (empty(BaseObject::getApp()->queue)) {
1264 $queue = BaseObject::getApp()->queue;
1266 $retrial = $queue['retrial'];
1268 $priority = $queue['priority'];
1270 if ($retrial > 14) {
1271 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1275 // Calculate the delay until the next trial
1276 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1277 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1279 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1280 $priority = PRIORITY_MEDIUM;
1281 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1282 $priority = PRIORITY_LOW;
1283 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1284 $priority = PRIORITY_NEGLIGIBLE;
1287 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1289 $stamp = (float)microtime(true);
1290 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1291 DBA::update('workerqueue', $fields, ['id' => $id]);
1292 self::$db_duration += (microtime(true) - $stamp);
1293 self::$db_duration_write += (microtime(true) - $stamp);
1297 * Log active processes into the "process" table
1299 * @brief Log active processes into the "process" table
1301 public static function startProcess()
1303 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1305 $command = basename($trace[0]['file']);
1307 Process::deleteInactive();
1309 Process::insert($command);
1313 * Remove the active process from the "process" table
1315 * @brief Remove the active process from the "process" table
1317 * @throws \Exception
1319 public static function endProcess()
1321 return Process::deleteByPid();
1325 * Set the flag if some job is waiting
1327 * @brief Set the flag if some job is waiting
1328 * @param boolean $jobs Is there a waiting job?
1329 * @throws \Exception
1331 public static function IPCSetJobState($jobs)
1333 $stamp = (float)microtime(true);
1334 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1335 self::$db_duration += (microtime(true) - $stamp);
1336 self::$db_duration_write += (microtime(true) - $stamp);
1340 * Checks if some worker job waits to be executed
1342 * @brief Checks if some worker job waits to be executed
1344 * @throws \Exception
1346 public static function IPCJobsExists()
1348 $stamp = (float)microtime(true);
1349 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1350 self::$db_duration += (microtime(true) - $stamp);
1352 // When we don't have a row, no job is running
1353 if (!DBA::isResult($row)) {
1357 return (bool)$row['jobs'];