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 + 30)) {
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.
414 $dbtotal = number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4);
415 $dbcount = number_format(self::$db_duration_count, 4);
416 $dbstat = number_format(self::$db_duration_stat, 4);
417 $dbwrite = number_format(self::$db_duration_write, 4);
418 $dblock = number_format(self::$lock_duration, 4);
419 $rest = number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4);
420 $exec = number_format($duration, 4);
422 Logger::info('Performance:', ['total' => $dbtotal, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'block' => $dblock, 'rest' => $rest, 'exec' => $exec]);
424 self::$up_start = microtime(true);
425 self::$db_duration = 0;
426 self::$db_duration_count = 0;
427 self::$db_duration_stat = 0;
428 self::$db_duration_write = 0;
429 self::$lock_duration = 0;
431 if ($duration > 3600) {
432 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
433 } elseif ($duration > 600) {
434 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
435 } elseif ($duration > 300) {
436 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
437 } elseif ($duration > 120) {
438 Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
441 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".number_format($duration, 4)." seconds. Process PID: ".$new_process_id);
443 // Write down the performance values into the log
444 if (Config::get("system", "profiler")) {
445 $duration = microtime(true)-$a->performance["start"];
448 if (Config::get("rendertime", "callstack")) {
449 if (isset($a->callstack["database"])) {
450 $o .= "\nDatabase Read:\n";
451 foreach ($a->callstack["database"] as $func => $time) {
452 $time = round($time, 3);
454 $o .= $func.": ".$time."\n";
458 if (isset($a->callstack["database_write"])) {
459 $o .= "\nDatabase Write:\n";
460 foreach ($a->callstack["database_write"] as $func => $time) {
461 $time = round($time, 3);
463 $o .= $func.": ".$time."\n";
467 if (isset($a->callstack["dache"])) {
468 $o .= "\nCache Read:\n";
469 foreach ($a->callstack["dache"] as $func => $time) {
470 $time = round($time, 3);
472 $o .= $func.": ".$time."\n";
476 if (isset($a->callstack["dache_write"])) {
477 $o .= "\nCache Write:\n";
478 foreach ($a->callstack["dache_write"] as $func => $time) {
479 $time = round($time, 3);
481 $o .= $func.": ".$time."\n";
485 if (isset($a->callstack["network"])) {
486 $o .= "\nNetwork:\n";
487 foreach ($a->callstack["network"] as $func => $time) {
488 $time = round($time, 3);
490 $o .= $func.": ".$time."\n";
497 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
498 "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
499 number_format($a->performance["database"] - $a->performance["database_write"], 2),
500 number_format($a->performance["database_write"], 2),
501 number_format($a->performance["cache"], 2),
502 number_format($a->performance["cache_write"], 2),
503 number_format($a->performance["network"], 2),
504 number_format($a->performance["file"], 2),
505 number_format($duration - ($a->performance["database"]
506 + $a->performance["cache"] + $a->performance["cache_write"]
507 + $a->performance["network"] + $a->performance["file"]), 2),
508 number_format($duration, 2)
514 $cooldown = Config::get("system", "worker_cooldown", 0);
517 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
523 * @brief Checks if the number of database connections has reached a critical limit.
525 * @return bool Are more than 3/4 of the maximum connections used?
526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
528 private static function maxConnectionsReached()
530 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
531 $max = Config::get("system", "max_connections");
533 // Fetch the percentage level where the worker will get active
534 $maxlevel = Config::get("system", "max_connections_level", 75);
537 // the maximum number of possible user connections can be a system variable
538 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
539 if (DBA::isResult($r)) {
542 // Or it can be granted. This overrides the system variable
543 $stamp = (float)microtime(true);
544 $r = DBA::p('SHOW GRANTS');
545 self::$db_duration += (microtime(true) - $stamp);
546 while ($grants = DBA::fetch($r)) {
547 $grant = array_pop($grants);
548 if (stristr($grant, "GRANT USAGE ON")) {
549 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
557 // If $max is set we will use the processlist to determine the current number of connections
558 // The processlist only shows entries of the current user
560 $stamp = (float)microtime(true);
561 $r = DBA::p('SHOW PROCESSLIST');
562 self::$db_duration += (microtime(true) - $stamp);
563 $used = DBA::numRows($r);
566 Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
568 $level = ($used / $max) * 100;
570 if ($level >= $maxlevel) {
571 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
576 // We will now check for the system values.
577 // This limit could be reached although the user limits are fine.
578 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
579 if (!DBA::isResult($r)) {
582 $max = intval($r["Value"]);
586 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
587 if (!DBA::isResult($r)) {
590 $used = intval($r["Value"]);
594 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
596 $level = $used / $max * 100;
598 if ($level < $maxlevel) {
601 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
606 * @brief fix the queue entry if the worker process died
610 private static function killStaleWorkers()
612 $stamp = (float)microtime(true);
613 $entries = DBA::select(
615 ['id', 'pid', 'executed', 'priority', 'parameter'],
616 ['NOT `done` AND `pid` != 0'],
617 ['order' => ['priority', 'created']]
619 self::$db_duration += (microtime(true) - $stamp);
621 while ($entry = DBA::fetch($entries)) {
622 if (!posix_kill($entry["pid"], 0)) {
623 $stamp = (float)microtime(true);
626 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
627 ['id' => $entry["id"]]
629 self::$db_duration += (microtime(true) - $stamp);
630 self::$db_duration_write += (microtime(true) - $stamp);
632 // Kill long running processes
633 // Check if the priority is in a valid range
634 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
635 $entry["priority"] = PRIORITY_MEDIUM;
638 // Define the maximum durations
639 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
640 $max_duration = $max_duration_defaults[$entry["priority"]];
642 $argv = json_decode($entry["parameter"], true);
643 $argv[0] = basename($argv[0]);
645 // How long is the process already running?
646 $duration = (time() - strtotime($entry["executed"])) / 60;
647 if ($duration > $max_duration) {
648 Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
649 posix_kill($entry["pid"], SIGTERM);
651 // We killed the stale process.
652 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
653 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
654 $new_priority = $entry["priority"];
655 if ($entry["priority"] == PRIORITY_HIGH) {
656 $new_priority = PRIORITY_MEDIUM;
657 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
658 $new_priority = PRIORITY_LOW;
659 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
660 $new_priority = PRIORITY_NEGLIGIBLE;
662 $stamp = (float)microtime(true);
665 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
666 ['id' => $entry["id"]]
668 self::$db_duration += (microtime(true) - $stamp);
669 self::$db_duration_write += (microtime(true) - $stamp);
671 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);
678 * @brief Checks if the number of active workers exceeds the given limits
680 * @return bool Are there too much workers running?
681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683 private static function tooMuchWorkers()
685 $queues = Config::get("system", "worker_queues", 4);
687 $maxqueues = $queues;
689 $active = self::activeWorkers();
691 // Decrease the number of workers at higher load
692 $load = System::currentLoad();
694 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
696 /* Default exponent 3 causes queues to rapidly decrease as load increases.
697 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
698 * For some environments, this rapid decrease is not needed.
699 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
701 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
702 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
703 $queues = intval(ceil($slope * $maxqueues));
707 if (Config::get('system', 'worker_jpm')) {
708 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
709 $jobs_per_minute = [];
710 foreach ($intervals as $interval) {
711 if ($interval == 0) {
714 $interval = (int)$interval;
717 $stamp = (float)microtime(true);
718 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
719 self::$db_duration += (microtime(true) - $stamp);
720 self::$db_duration_stat += (microtime(true) - $stamp);
721 if ($job = DBA::fetch($jobs)) {
722 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
726 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
729 // Create a list of queue entries grouped by their priority
730 $listitem = [0 => ''];
732 $idle_workers = $active;
734 $deferred = self::deferredEntries();
736 if (Config::get('system', 'worker_debug')) {
737 $waiting_processes = 0;
738 // Now adding all processes with workerqueue entries
739 $stamp = (float)microtime(true);
740 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
741 self::$db_duration += (microtime(true) - $stamp);
742 self::$db_duration_stat += (microtime(true) - $stamp);
743 while ($entry = DBA::fetch($jobs)) {
744 $stamp = (float)microtime(true);
745 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
746 self::$db_duration += (microtime(true) - $stamp);
747 self::$db_duration_stat += (microtime(true) - $stamp);
748 if ($process = DBA::fetch($processes)) {
749 $idle_workers -= $process["running"];
750 $waiting_processes += $entry["entries"];
751 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
753 DBA::close($processes);
756 $entries = $deferred + $waiting_processes;
758 $entries = self::totalEntries();
759 $waiting_processes = max(0, $entries - $deferred);
760 $stamp = (float)microtime(true);
761 $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`");
762 self::$db_duration += (microtime(true) - $stamp);
763 self::$db_duration_stat += (microtime(true) - $stamp);
765 while ($entry = DBA::fetch($jobs)) {
766 $idle_workers -= $entry["running"];
767 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
772 $listitem[0] = "0:" . max(0, $idle_workers);
774 $processlist .= ' ('.implode(', ', $listitem).')';
776 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
777 $top_priority = self::highestPriority();
778 $high_running = self::processWithPriorityActive($top_priority);
780 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
781 Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
782 $queues = $active + 1;
786 Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
788 // Are there fewer workers running as possible? Then fork a new one.
789 if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
790 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
791 if (Config::get('system', 'worker_daemon_mode', false)) {
792 self::IPCSetJobState(true);
799 // if there are too much worker, we don't spawn a new one.
800 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
801 self::IPCSetJobState(false);
804 return $active > $queues;
808 * @brief Returns the number of active worker processes
810 * @return integer Number of active worker processes
813 private static function activeWorkers()
815 $stamp = (float)microtime(true);
816 $count = DBA::count('process', ['command' => 'Worker.php']);
817 self::$db_duration += (microtime(true) - $stamp);
822 * @brief Returns waiting jobs for the current process id
824 * @return array waiting workerqueue jobs
827 private static function getWaitingJobForPID()
829 $stamp = (float)microtime(true);
830 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
831 self::$db_duration += (microtime(true) - $stamp);
832 if (DBA::isResult($r)) {
833 return DBA::toArray($r);
841 * @brief Returns the next jobs that should be executed
843 * @return array array with next jobs
846 private static function nextProcess()
848 $priority = self::nextPriority();
849 if (empty($priority)) {
850 Logger::info('No tasks found');
854 if ($priority <= PRIORITY_MEDIUM) {
855 $limit = Config::get('system', 'worker_fetch_limit', 1);
861 $stamp = (float)microtime(true);
862 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
863 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
864 self::$db_duration += (microtime(true) - $stamp);
865 while ($task = DBA::fetch($tasks)) {
866 $ids[] = $task['id'];
870 Logger::info('Found:', ['id' => $ids, 'priority' => $priority]);
875 * @brief Returns the priority of the next workerqueue job
877 * @return string priority
880 private static function nextPriority()
883 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
884 foreach ($priorities as $priority) {
885 $stamp = (float)microtime(true);
886 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
887 $waiting[$priority] = true;
889 self::$db_duration += (microtime(true) - $stamp);
892 if (!empty($waiting[PRIORITY_CRITICAL])) {
893 return PRIORITY_CRITICAL;
898 $stamp = (float)microtime(true);
899 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
900 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
901 WHERE NOT `done` GROUP BY `priority`");
902 self::$db_duration += (microtime(true) - $stamp);
903 while ($process = DBA::fetch($processes)) {
904 $running[$process['priority']] = $process['running'];
905 $running_total += $process['running'];
907 DBA::close($processes);
909 foreach ($priorities as $priority) {
910 if (!empty($waiting[$priority]) && empty($running[$priority])) {
911 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
916 $active = max(self::activeWorkers(), $running_total);
917 $priorities = max(count($waiting), count($running));
921 for ($i = 1; $i <= $priorities; ++$i) {
922 $total += pow($i, $exponent);
926 for ($i = 1; $i <= $priorities; ++$i) {
927 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
931 foreach ($running as $priority => $workers) {
932 if ($workers < $limit[$i++]) {
933 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
938 if (!empty($waiting)) {
939 $priority = array_shift(array_keys($waiting));
940 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
948 * @brief Find and claim the next worker process for us
950 * @return boolean Have we found something?
951 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953 private static function findWorkerProcesses()
957 $ids = self::nextProcess();
959 // If there is no result we check without priority limit
961 $stamp = (float)microtime(true);
962 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
963 $result = DBA::select('workerqueue', ['id'], $condition, ['limit' => 1, 'order' => ['priority', 'created']]);
964 self::$db_duration += (microtime(true) - $stamp);
966 while ($id = DBA::fetch($result)) {
973 $stamp = (float)microtime(true);
974 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
975 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
976 self::$db_duration += (microtime(true) - $stamp);
977 self::$db_duration_write += (microtime(true) - $stamp);
984 * @brief Returns the next worker process
986 * @return string SQL statement
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 public static function workerProcess()
991 // There can already be jobs for us in the queue.
992 $waiting = self::getWaitingJobForPID();
993 if (!empty($waiting)) {
997 $stamp = (float)microtime(true);
998 if (!Lock::acquire('worker_process')) {
1001 self::$lock_duration += (microtime(true) - $stamp);
1003 $found = self::findWorkerProcesses();
1005 Lock::release('worker_process');
1008 $stamp = (float)microtime(true);
1009 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1010 self::$db_duration += (microtime(true) - $stamp);
1011 return DBA::toArray($r);
1017 * @brief Removes a workerqueue entry from the current process
1019 * @throws \Exception
1021 public static function unclaimProcess()
1023 $mypid = getmypid();
1025 $stamp = (float)microtime(true);
1026 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1027 self::$db_duration += (microtime(true) - $stamp);
1028 self::$db_duration_write += (microtime(true) - $stamp);
1032 * @brief Call the front end worker
1034 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1036 public static function callWorker()
1038 if (!Config::get("system", "frontend_worker")) {
1042 $url = System::baseUrl()."/worker";
1043 Network::fetchUrl($url, false, $redirects, 1);
1047 * @brief Call the front end worker if there aren't any active
1049 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1051 public static function executeIfIdle()
1053 if (!Config::get("system", "frontend_worker")) {
1057 // Do we have "proc_open"? Then we can fork the worker
1058 if (function_exists("proc_open")) {
1059 // When was the last time that we called the worker?
1060 // Less than one minute? Then we quit
1061 if ((time() - Config::get("system", "worker_started")) < 60) {
1065 Config::set("system", "worker_started", time());
1067 // Do we have enough running workers? Then we quit here.
1068 if (self::tooMuchWorkers()) {
1069 // Cleaning dead processes
1070 self::killStaleWorkers();
1071 Process::deleteInactive();
1078 Logger::log('Call worker', Logger::DEBUG);
1079 self::spawnWorker();
1083 // We cannot execute background processes.
1084 // We now run the processes from the frontend.
1085 // This won't work with long running processes.
1088 self::clearProcesses();
1090 $workers = self::activeWorkers();
1092 if ($workers == 0) {
1098 * @brief Removes long running worker processes
1100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102 public static function clearProcesses()
1104 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1106 /// @todo We should clean up the corresponding workerqueue entries as well
1107 $stamp = (float)microtime(true);
1108 $condition = ["`created` < ? AND `command` = 'worker.php'",
1109 DateTimeFormat::utc("now - ".$timeout." minutes")];
1110 DBA::delete('process', $condition);
1111 self::$db_duration = (microtime(true) - $stamp);
1112 self::$db_duration_write += (microtime(true) - $stamp);
1116 * @brief Runs the cron processes
1118 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1120 private static function runCron()
1122 Logger::log('Add cron entries', Logger::DEBUG);
1124 // Check for spooled items
1125 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1127 // Run the cron job that calls all other jobs
1128 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1130 // Cleaning dead processes
1131 self::killStaleWorkers();
1135 * @brief Spawns a new worker
1136 * @param bool $do_cron
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 public static function spawnWorker($do_cron = false)
1142 $command = 'bin/worker.php';
1144 $args = ['no_cron' => !$do_cron];
1146 get_app()->proc_run($command, $args);
1148 // after spawning we have to remove the flag.
1149 if (Config::get('system', 'worker_daemon_mode', false)) {
1150 self::IPCSetJobState(false);
1155 * @brief Adds tasks to the worker queue
1157 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1159 * next args are passed as $cmd command line
1160 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1161 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1163 * @return boolean "false" if proc_run couldn't be executed
1164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1165 * @note $cmd and string args are surrounded with ""
1171 public static function add($cmd)
1173 $args = func_get_args();
1175 if (!count($args)) {
1179 $arr = ['args' => $args, 'run_cmd' => true];
1181 Hook::callAll("proc_run", $arr);
1182 if (!$arr['run_cmd'] || !count($args)) {
1186 $priority = PRIORITY_MEDIUM;
1187 $dont_fork = Config::get("system", "worker_dont_fork", false);
1188 $created = DateTimeFormat::utcNow();
1189 $force_priority = false;
1191 $run_parameter = array_shift($args);
1193 if (is_int($run_parameter)) {
1194 $priority = $run_parameter;
1195 } elseif (is_array($run_parameter)) {
1196 if (isset($run_parameter['priority'])) {
1197 $priority = $run_parameter['priority'];
1199 if (isset($run_parameter['created'])) {
1200 $created = $run_parameter['created'];
1202 if (isset($run_parameter['dont_fork'])) {
1203 $dont_fork = $run_parameter['dont_fork'];
1205 if (isset($run_parameter['force_priority'])) {
1206 $force_priority = $run_parameter['force_priority'];
1210 $parameters = json_encode($args);
1211 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1213 // Quit if there was a database error - a precaution for the update process to 3.5.3
1214 if (DBA::errorNo() != 0) {
1219 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1220 } elseif ($force_priority) {
1221 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1224 // Should we quit and wait for the worker to be called as a cronjob?
1229 // If there is a lock then we don't have to check for too much worker
1230 if (!Lock::acquire('worker', 0)) {
1234 // If there are already enough workers running, don't fork another one
1235 $quit = self::tooMuchWorkers();
1236 Lock::release('worker');
1242 // We tell the daemon that a new job entry exists
1243 if (Config::get('system', 'worker_daemon_mode', false)) {
1244 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1248 // Now call the worker to execute the jobs that we just added to the queue
1249 self::spawnWorker();
1255 * Defers the current worker entry
1257 public static function defer()
1259 if (empty(BaseObject::getApp()->queue)) {
1263 $queue = BaseObject::getApp()->queue;
1265 $retrial = $queue['retrial'];
1267 $priority = $queue['priority'];
1269 if ($retrial > 14) {
1270 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1274 // Calculate the delay until the next trial
1275 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1276 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1278 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1279 $priority = PRIORITY_MEDIUM;
1280 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1281 $priority = PRIORITY_LOW;
1282 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1283 $priority = PRIORITY_NEGLIGIBLE;
1286 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1288 $stamp = (float)microtime(true);
1289 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1290 DBA::update('workerqueue', $fields, ['id' => $id]);
1291 self::$db_duration += (microtime(true) - $stamp);
1292 self::$db_duration_write += (microtime(true) - $stamp);
1296 * Log active processes into the "process" table
1298 * @brief Log active processes into the "process" table
1300 public static function startProcess()
1302 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1304 $command = basename($trace[0]['file']);
1306 Process::deleteInactive();
1308 Process::insert($command);
1312 * Remove the active process from the "process" table
1314 * @brief Remove the active process from the "process" table
1316 * @throws \Exception
1318 public static function endProcess()
1320 return Process::deleteByPid();
1324 * Set the flag if some job is waiting
1326 * @brief Set the flag if some job is waiting
1327 * @param boolean $jobs Is there a waiting job?
1328 * @throws \Exception
1330 public static function IPCSetJobState($jobs)
1332 $stamp = (float)microtime(true);
1333 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1334 self::$db_duration += (microtime(true) - $stamp);
1335 self::$db_duration_write += (microtime(true) - $stamp);
1339 * Checks if some worker job waits to be executed
1341 * @brief Checks if some worker job waits to be executed
1343 * @throws \Exception
1345 public static function IPCJobsExists()
1347 $stamp = (float)microtime(true);
1348 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1349 self::$db_duration += (microtime(true) - $stamp);
1351 // When we don't have a row, no job is running
1352 if (!DBA::isResult($row)) {
1356 return (bool)$row['jobs'];