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;
31 private static $mode = 0;
34 * @brief Processes the tasks that are in the workerqueue table
36 * @param boolean $run_cron Should the cron processes be executed?
38 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
40 public static function processQueue($run_cron = true)
44 // Ensure that all "strtotime" operations do run timezone independent
45 date_default_timezone_set('UTC');
47 self::$up_start = microtime(true);
49 // At first check the maximum load. We shouldn't continue with a high load
50 if ($a->isMaxLoadReached()) {
51 Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
55 // We now start the process. This is done after the load check since this could increase the load.
58 // Kill stale processes every 5 minutes
59 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
60 if (time() > ($last_cleanup + 300)) {
61 Config::set('system', 'worker_last_cleaned', time());
62 self::killStaleWorkers();
65 // Count active workers and compare them with a maximum value that depends on the load
66 if (self::tooMuchWorkers()) {
67 Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
71 // Do we have too few memory?
72 if ($a->isMinMemoryReached()) {
73 Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
77 // Possibly there are too much database connections
78 if (self::maxConnectionsReached()) {
79 Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
83 // Possibly there are too much database processes that block the system
84 if ($a->isMaxProcessesReached()) {
85 Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
89 // Now we start additional cron processes if we should do so
97 // We fetch the next queue entry that is about to be executed
98 while ($r = self::workerProcess()) {
99 foreach ($r as $entry) {
100 // Assure that the priority is an integer value
101 $entry['priority'] = (int)$entry['priority'];
103 // The work will be done
104 if (!self::execute($entry)) {
105 Logger::log('Process execution failed, quitting.', Logger::DEBUG);
109 // If possible we will fetch new jobs for this worker
110 if (!self::getWaitingJobForPID() && Lock::acquire('worker_process', 0)) {
111 self::findWorkerProcesses();
112 Lock::release('worker_process');
119 // Quit the worker once every cron interval
120 if (time() > ($starttime + Config::get('system', 'cron_interval'))) {
121 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
125 // To avoid the quitting of multiple workers only one worker at a time will execute the check
126 if (Lock::acquire('worker', 0)) {
127 // Count active workers and compare them with a maximum value that depends on the load
128 if (self::tooMuchWorkers()) {
129 Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
130 Lock::release('worker');
135 if ($a->isMinMemoryReached()) {
136 Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
137 Lock::release('worker');
140 Lock::release('worker');
144 // Cleaning up. Possibly not needed, but it doesn't harm anything.
145 if (Config::get('system', 'worker_daemon_mode', false)) {
146 self::IPCSetJobState(false);
148 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
152 * @brief Check if non executed tasks do exist in the worker queue
154 * @return boolean Returns "true" if tasks are existing
157 private static function entriesExists()
159 $stamp = (float)microtime(true);
160 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
161 self::$db_duration += (microtime(true) - $stamp);
166 * @brief Returns the number of deferred entries in the worker queue
168 * @return integer Number of deferred entries in the worker queue
171 private static function deferredEntries()
173 $stamp = (float)microtime(true);
174 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
175 self::$db_duration += (microtime(true) - $stamp);
176 self::$db_duration_count += (microtime(true) - $stamp);
181 * @brief Returns the number of non executed entries in the worker queue
183 * @return integer Number of non executed entries in the worker queue
186 private static function totalEntries()
188 $stamp = (float)microtime(true);
189 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
190 self::$db_duration += (microtime(true) - $stamp);
191 self::$db_duration_count += (microtime(true) - $stamp);
196 * @brief Returns the highest priority in the worker queue that isn't executed
198 * @return integer Number of active worker processes
201 private static function highestPriority()
203 $stamp = (float)microtime(true);
204 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
205 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
206 self::$db_duration += (microtime(true) - $stamp);
207 if (DBA::isResult($workerqueue)) {
208 return $workerqueue["priority"];
215 * @brief Returns if a process with the given priority is running
217 * @param integer $priority The priority that should be checked
219 * @return integer Is there a process running with that priority?
222 private static function processWithPriorityActive($priority)
224 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
225 return DBA::exists('workerqueue', $condition);
229 * @brief Execute a worker entry
231 * @param array $queue Workerqueue entry
233 * @return boolean "true" if further processing should be stopped
234 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
236 public static function execute($queue)
242 // Quit when in maintenance
243 if (Config::get('system', 'maintenance', false, true)) {
244 Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
248 // Constantly check the number of parallel database processes
249 if ($a->isMaxProcessesReached()) {
250 Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
254 // Constantly check the number of available database connections to let the frontend be accessible at any time
255 if (self::maxConnectionsReached()) {
256 Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
260 $argv = json_decode($queue["parameter"], true);
262 // Check for existance and validity of the include file
265 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
266 // We constantly update the "executed" date every minute to avoid being killed too soon
267 if (!isset(self::$last_update)) {
268 self::$last_update = strtotime($queue["executed"]);
271 $age = (time() - self::$last_update) / 60;
272 self::$last_update = time();
275 $stamp = (float)microtime(true);
276 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
277 self::$db_duration += (microtime(true) - $stamp);
278 self::$db_duration_write += (microtime(true) - $stamp);
283 self::execFunction($queue, $include, $argv, true);
285 $stamp = (float)microtime(true);
286 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
287 if (DBA::update('workerqueue', ['done' => true], $condition)) {
288 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
290 self::$db_duration = (microtime(true) - $stamp);
291 self::$db_duration_write += (microtime(true) - $stamp);
296 // The script could be provided as full path or only with the function name
297 if ($include == basename($include)) {
298 $include = "include/".$include.".php";
301 if (!validate_include($include)) {
302 Logger::log("Include file ".$argv[0]." is not valid!");
303 $stamp = (float)microtime(true);
304 DBA::delete('workerqueue', ['id' => $queue["id"]]);
305 self::$db_duration = (microtime(true) - $stamp);
306 self::$db_duration_write += (microtime(true) - $stamp);
310 require_once $include;
312 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
314 if (function_exists($funcname)) {
315 // We constantly update the "executed" date every minute to avoid being killed too soon
316 if (!isset(self::$last_update)) {
317 self::$last_update = strtotime($queue["executed"]);
320 $age = (time() - self::$last_update) / 60;
321 self::$last_update = time();
324 $stamp = (float)microtime(true);
325 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
326 self::$db_duration += (microtime(true) - $stamp);
327 self::$db_duration_write += (microtime(true) - $stamp);
330 self::execFunction($queue, $funcname, $argv, false);
332 $stamp = (float)microtime(true);
333 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
334 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
336 self::$db_duration = (microtime(true) - $stamp);
337 self::$db_duration_write += (microtime(true) - $stamp);
339 Logger::log("Function ".$funcname." does not exist");
340 $stamp = (float)microtime(true);
341 DBA::delete('workerqueue', ['id' => $queue["id"]]);
342 self::$db_duration = (microtime(true) - $stamp);
343 self::$db_duration_write += (microtime(true) - $stamp);
350 * @brief Execute a function from the queue
352 * @param array $queue Workerqueue entry
353 * @param string $funcname name of the function
354 * @param array $argv Array of values to be passed to the function
355 * @param boolean $method_call boolean
357 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
359 private static function execFunction($queue, $funcname, $argv, $method_call)
365 $argc = count($argv);
367 // Currently deactivated, since the new logger doesn't support this
368 //$new_process_id = System::processID("wrk");
369 $new_process_id = '';
371 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
373 $stamp = (float)microtime(true);
375 // We use the callstack here to analyze the performance of executed worker entries.
376 // For this reason the variables have to be initialized.
377 if (Config::get("system", "profiler")) {
378 $a->performance["start"] = microtime(true);
379 $a->performance["database"] = 0;
380 $a->performance["database_write"] = 0;
381 $a->performance["cache"] = 0;
382 $a->performance["cache_write"] = 0;
383 $a->performance["network"] = 0;
384 $a->performance["file"] = 0;
385 $a->performance["rendering"] = 0;
386 $a->performance["parser"] = 0;
387 $a->performance["marktime"] = 0;
388 $a->performance["markstart"] = microtime(true);
392 // For better logging create a new process id for every worker call
393 // But preserve the old one for the worker
394 $old_process_id = $a->process_id;
395 $a->process_id = $new_process_id;
398 $up_duration = microtime(true) - self::$up_start;
400 // Reset global data to avoid interferences
404 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
406 $funcname($argv, $argc);
409 $a->process_id = $old_process_id;
412 $duration = (microtime(true) - $stamp);
414 /* With these values we can analyze how effective the worker is.
415 * The database and rest time should be low since this is the unproductive time.
416 * The execution time is the productive time.
417 * By changing parameters like the maximum number of workers we can check the effectivness.
419 $dbtotal = round(self::$db_duration, 2);
420 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
421 $dbcount = round(self::$db_duration_count, 2);
422 $dbstat = round(self::$db_duration_stat, 2);
423 $dbwrite = round(self::$db_duration_write, 2);
424 $dblock = round(self::$lock_duration, 2);
425 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
426 $exec = round($duration, 2);
428 Logger::info('Performance:', ['mode' => self::$mode, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
430 self::$up_start = microtime(true);
431 self::$db_duration = 0;
432 self::$db_duration_count = 0;
433 self::$db_duration_stat = 0;
434 self::$db_duration_write = 0;
435 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 ".number_format($duration, 4)." 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 * @return bool Are there too much workers running?
688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
690 private static function tooMuchWorkers()
692 $queues = Config::get("system", "worker_queues", 4);
694 $maxqueues = $queues;
696 $active = self::activeWorkers();
698 // Decrease the number of workers at higher load
699 $load = System::currentLoad();
701 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
703 /* Default exponent 3 causes queues to rapidly decrease as load increases.
704 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
705 * For some environments, this rapid decrease is not needed.
706 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
708 $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
709 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
710 $queues = intval(ceil($slope * $maxqueues));
714 if (Config::get('system', 'worker_jpm')) {
715 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
716 $jobs_per_minute = [];
717 foreach ($intervals as $interval) {
718 if ($interval == 0) {
721 $interval = (int)$interval;
724 $stamp = (float)microtime(true);
725 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
726 self::$db_duration += (microtime(true) - $stamp);
727 self::$db_duration_stat += (microtime(true) - $stamp);
728 if ($job = DBA::fetch($jobs)) {
729 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
733 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
736 // Create a list of queue entries grouped by their priority
737 $listitem = [0 => ''];
739 $idle_workers = $active;
741 $deferred = self::deferredEntries();
743 if (Config::get('system', 'worker_debug')) {
744 $waiting_processes = 0;
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 $waiting_processes += $entry["entries"];
758 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
760 DBA::close($processes);
763 $entries = $deferred + $waiting_processes;
765 $entries = self::totalEntries();
766 $waiting_processes = max(0, $entries - $deferred);
767 $stamp = (float)microtime(true);
768 $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`");
769 self::$db_duration += (microtime(true) - $stamp);
770 self::$db_duration_stat += (microtime(true) - $stamp);
772 while ($entry = DBA::fetch($jobs)) {
773 $idle_workers -= $entry["running"];
774 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
779 $listitem[0] = "0:" . max(0, $idle_workers);
781 $processlist .= ' ('.implode(', ', $listitem).')';
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 . "/" . $waiting_processes . $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 Returns waiting jobs for the current process id
831 * @return array waiting workerqueue jobs
834 private static function getWaitingJobForPID()
836 $stamp = (float)microtime(true);
837 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
838 self::$db_duration += (microtime(true) - $stamp);
839 if (DBA::isResult($r)) {
840 return DBA::toArray($r);
848 * @brief Returns the next jobs that should be executed
850 * @return array array with next jobs
853 private static function nextProcess()
855 $priority = self::nextPriority();
856 if (empty($priority)) {
857 Logger::info('No tasks found');
861 if ($priority <= PRIORITY_MEDIUM) {
862 $limit = Config::get('system', 'worker_fetch_limit', 1);
868 $stamp = (float)microtime(true);
869 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
870 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
871 self::$db_duration += (microtime(true) - $stamp);
872 while ($task = DBA::fetch($tasks)) {
873 $ids[] = $task['id'];
877 Logger::info('Found:', ['id' => $ids, 'priority' => $priority]);
882 * @brief Returns the priority of the next workerqueue job
884 * @return string priority
887 private static function nextPriority()
890 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
891 foreach ($priorities as $priority) {
892 $stamp = (float)microtime(true);
893 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
894 $waiting[$priority] = true;
896 self::$db_duration += (microtime(true) - $stamp);
899 if (!empty($waiting[PRIORITY_CRITICAL])) {
900 return PRIORITY_CRITICAL;
905 $stamp = (float)microtime(true);
906 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
907 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
908 WHERE NOT `done` GROUP BY `priority`");
909 self::$db_duration += (microtime(true) - $stamp);
910 while ($process = DBA::fetch($processes)) {
911 $running[$process['priority']] = $process['running'];
912 $running_total += $process['running'];
914 DBA::close($processes);
916 foreach ($priorities as $priority) {
917 if (!empty($waiting[$priority]) && empty($running[$priority])) {
918 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
923 $active = max(self::activeWorkers(), $running_total);
924 $priorities = max(count($waiting), count($running));
928 for ($i = 1; $i <= $priorities; ++$i) {
929 $total += pow($i, $exponent);
933 for ($i = 1; $i <= $priorities; ++$i) {
934 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
938 foreach ($running as $priority => $workers) {
939 if ($workers < $limit[$i++]) {
940 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
945 if (!empty($waiting)) {
946 $priority = array_shift(array_keys($waiting));
947 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
955 * @brief Find and claim the next worker process for us
957 * @return boolean Have we found something?
958 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
960 private static function findWorkerProcesses()
964 $ids = self::nextProcess();
966 // If there is no result we check without priority limit
968 $stamp = (float)microtime(true);
969 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
970 $result = DBA::select('workerqueue', ['id'], $condition, ['limit' => 1, 'order' => ['priority', 'created']]);
971 self::$db_duration += (microtime(true) - $stamp);
973 while ($id = DBA::fetch($result)) {
980 $stamp = (float)microtime(true);
981 $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
982 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
983 self::$db_duration += (microtime(true) - $stamp);
984 self::$db_duration_write += (microtime(true) - $stamp);
991 * @brief Returns the next worker process
993 * @return string SQL statement
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996 public static function workerProcess()
998 // There can already be jobs for us in the queue.
999 $waiting = self::getWaitingJobForPID();
1000 if (!empty($waiting)) {
1004 $stamp = (float)microtime(true);
1005 if (!Lock::acquire('worker_process')) {
1008 self::$lock_duration += (microtime(true) - $stamp);
1010 $found = self::findWorkerProcesses();
1012 Lock::release('worker_process');
1015 $stamp = (float)microtime(true);
1016 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1017 self::$db_duration += (microtime(true) - $stamp);
1018 return DBA::toArray($r);
1024 * @brief Removes a workerqueue entry from the current process
1026 * @throws \Exception
1028 public static function unclaimProcess()
1030 $mypid = getmypid();
1032 $stamp = (float)microtime(true);
1033 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1034 self::$db_duration += (microtime(true) - $stamp);
1035 self::$db_duration_write += (microtime(true) - $stamp);
1039 * @brief Call the front end worker
1041 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 public static function callWorker()
1045 if (!Config::get("system", "frontend_worker")) {
1049 $url = System::baseUrl()."/worker";
1050 Network::fetchUrl($url, false, $redirects, 1);
1054 * @brief Call the front end worker if there aren't any active
1056 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1058 public static function executeIfIdle()
1060 if (!Config::get("system", "frontend_worker")) {
1064 // Do we have "proc_open"? Then we can fork the worker
1065 if (function_exists("proc_open")) {
1066 // When was the last time that we called the worker?
1067 // Less than one minute? Then we quit
1068 if ((time() - Config::get("system", "worker_started")) < 60) {
1072 Config::set("system", "worker_started", time());
1074 // Do we have enough running workers? Then we quit here.
1075 if (self::tooMuchWorkers()) {
1076 // Cleaning dead processes
1077 self::killStaleWorkers();
1078 Process::deleteInactive();
1085 Logger::log('Call worker', Logger::DEBUG);
1086 self::spawnWorker();
1090 // We cannot execute background processes.
1091 // We now run the processes from the frontend.
1092 // This won't work with long running processes.
1095 self::clearProcesses();
1097 $workers = self::activeWorkers();
1099 if ($workers == 0) {
1105 * @brief Removes long running worker processes
1107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109 public static function clearProcesses()
1111 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1113 /// @todo We should clean up the corresponding workerqueue entries as well
1114 $stamp = (float)microtime(true);
1115 $condition = ["`created` < ? AND `command` = 'worker.php'",
1116 DateTimeFormat::utc("now - ".$timeout." minutes")];
1117 DBA::delete('process', $condition);
1118 self::$db_duration = (microtime(true) - $stamp);
1119 self::$db_duration_write += (microtime(true) - $stamp);
1123 * @brief Runs the cron processes
1125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127 private static function runCron()
1129 Logger::log('Add cron entries', Logger::DEBUG);
1131 // Check for spooled items
1132 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1134 // Run the cron job that calls all other jobs
1135 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1137 // Cleaning dead processes
1138 self::killStaleWorkers();
1142 * @brief Spawns a new worker
1143 * @param bool $do_cron
1145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1147 public static function spawnWorker($do_cron = false)
1149 $command = 'bin/worker.php';
1151 $args = ['no_cron' => !$do_cron];
1153 get_app()->proc_run($command, $args);
1155 // after spawning we have to remove the flag.
1156 if (Config::get('system', 'worker_daemon_mode', false)) {
1157 self::IPCSetJobState(false);
1162 * @brief Adds tasks to the worker queue
1164 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1166 * next args are passed as $cmd command line
1167 * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1168 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1170 * @return boolean "false" if proc_run couldn't be executed
1171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1172 * @note $cmd and string args are surrounded with ""
1178 public static function add($cmd)
1180 $args = func_get_args();
1182 if (!count($args)) {
1186 $arr = ['args' => $args, 'run_cmd' => true];
1188 Hook::callAll("proc_run", $arr);
1189 if (!$arr['run_cmd'] || !count($args)) {
1193 $priority = PRIORITY_MEDIUM;
1194 $dont_fork = Config::get("system", "worker_dont_fork", false);
1195 $created = DateTimeFormat::utcNow();
1196 $force_priority = false;
1198 $run_parameter = array_shift($args);
1200 if (is_int($run_parameter)) {
1201 $priority = $run_parameter;
1202 } elseif (is_array($run_parameter)) {
1203 if (isset($run_parameter['priority'])) {
1204 $priority = $run_parameter['priority'];
1206 if (isset($run_parameter['created'])) {
1207 $created = $run_parameter['created'];
1209 if (isset($run_parameter['dont_fork'])) {
1210 $dont_fork = $run_parameter['dont_fork'];
1212 if (isset($run_parameter['force_priority'])) {
1213 $force_priority = $run_parameter['force_priority'];
1217 $parameters = json_encode($args);
1218 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1220 // Quit if there was a database error - a precaution for the update process to 3.5.3
1221 if (DBA::errorNo() != 0) {
1226 DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1227 } elseif ($force_priority) {
1228 DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1231 // Should we quit and wait for the worker to be called as a cronjob?
1236 // If there is a lock then we don't have to check for too much worker
1237 if (!Lock::acquire('worker', 0)) {
1241 // If there are already enough workers running, don't fork another one
1242 $quit = self::tooMuchWorkers();
1243 Lock::release('worker');
1249 // We tell the daemon that a new job entry exists
1250 if (Config::get('system', 'worker_daemon_mode', false)) {
1251 // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1255 // Now call the worker to execute the jobs that we just added to the queue
1256 self::spawnWorker();
1262 * Defers the current worker entry
1264 public static function defer()
1266 if (empty(BaseObject::getApp()->queue)) {
1270 $queue = BaseObject::getApp()->queue;
1272 $retrial = $queue['retrial'];
1274 $priority = $queue['priority'];
1276 if ($retrial > 14) {
1277 Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1281 // Calculate the delay until the next trial
1282 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1283 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1285 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1286 $priority = PRIORITY_MEDIUM;
1287 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1288 $priority = PRIORITY_LOW;
1289 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1290 $priority = PRIORITY_NEGLIGIBLE;
1293 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1295 $stamp = (float)microtime(true);
1296 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1297 DBA::update('workerqueue', $fields, ['id' => $id]);
1298 self::$db_duration += (microtime(true) - $stamp);
1299 self::$db_duration_write += (microtime(true) - $stamp);
1303 * Log active processes into the "process" table
1305 * @brief Log active processes into the "process" table
1307 public static function startProcess()
1309 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1311 $command = basename($trace[0]['file']);
1313 Process::deleteInactive();
1315 Process::insert($command);
1319 * Remove the active process from the "process" table
1321 * @brief Remove the active process from the "process" table
1323 * @throws \Exception
1325 public static function endProcess()
1327 return Process::deleteByPid();
1331 * Set the flag if some job is waiting
1333 * @brief Set the flag if some job is waiting
1334 * @param boolean $jobs Is there a waiting job?
1335 * @throws \Exception
1337 public static function IPCSetJobState($jobs)
1339 $stamp = (float)microtime(true);
1340 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1341 self::$db_duration += (microtime(true) - $stamp);
1342 self::$db_duration_write += (microtime(true) - $stamp);
1346 * Checks if some worker job waits to be executed
1348 * @brief Checks if some worker job waits to be executed
1350 * @throws \Exception
1352 public static function IPCJobsExists()
1354 $stamp = (float)microtime(true);
1355 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1356 self::$db_duration += (microtime(true) - $stamp);
1358 // When we don't have a row, no job is running
1359 if (!DBA::isResult($row)) {
1363 return (bool)$row['jobs'];