3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
24 use Friendica\App\Mode;
26 use Friendica\Database\DBA;
28 use Friendica\Util\DateTimeFormat;
31 * Contains the class for the worker background job processing
35 const STATE_STARTUP = 1; // Worker is in startup. This takes most time.
36 const STATE_LONG_LOOP = 2; // Worker is processing the whole - long - loop.
37 const STATE_REFETCH = 3; // Worker had refetched jobs in the execution loop.
38 const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
40 const FAST_COMMANDS = ['APDelivery', 'Delivery'];
42 const LOCK_PROCESS = 'worker_process';
43 const LOCK_WORKER = 'worker';
45 private static $up_start;
46 private static $db_duration = 0;
47 private static $db_duration_count = 0;
48 private static $db_duration_write = 0;
49 private static $db_duration_stat = 0;
50 private static $lock_duration = 0;
51 private static $last_update;
52 private static $state;
53 private static $daemon_mode = null;
56 * Processes the tasks that are in the workerqueue table
58 * @param boolean $run_cron Should the cron processes be executed?
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public static function processQueue($run_cron = true)
64 // Ensure that all "strtotime" operations do run timezone independent
65 date_default_timezone_set('UTC');
67 self::$up_start = microtime(true);
69 // At first check the maximum load. We shouldn't continue with a high load
70 if (DI::process()->isMaxLoadReached()) {
71 Logger::notice('Pre check: maximum load reached, quitting.');
75 // We now start the process. This is done after the load check since this could increase the load.
76 DI::process()->start();
78 // Kill stale processes every 5 minutes
79 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
80 if (time() > ($last_cleanup + 300)) {
81 DI::config()->set('system', 'worker_last_cleaned', time());
82 self::killStaleWorkers();
85 // Check if the system is ready
86 if (!self::isReady()) {
90 // Now we start additional cron processes if we should do so
95 $last_check = $starttime = time();
96 self::$state = self::STATE_STARTUP;
97 $wait_interval = self::isDaemonMode() ? 360 : 10;
101 // We fetch the next queue entry that is about to be executed
102 while ($r = self::workerProcess()) {
103 // Don't refetch when a worker fetches tasks for multiple workers
104 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
105 foreach ($r as $entry) {
106 // Assure that the priority is an integer value
107 $entry['priority'] = (int)$entry['priority'];
109 // The work will be done
110 if (!self::execute($entry)) {
111 Logger::notice('Process execution failed, quitting.');
115 // Trying to fetch new processes - but only once when successful
116 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
117 self::findWorkerProcesses();
118 DI::lock()->release(self::LOCK_PROCESS);
119 self::$state = self::STATE_REFETCH;
122 self::$state = self::STATE_SHORT_LOOP;
126 // To avoid the quitting of multiple workers only one worker at a time will execute the check
127 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
128 self::$state = self::STATE_LONG_LOOP;
130 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
131 // Count active workers and compare them with a maximum value that depends on the load
132 if (self::tooMuchWorkers()) {
133 Logger::notice('Active worker limit reached, quitting.');
134 DI::lock()->release(self::LOCK_WORKER);
139 if (DI::process()->isMinMemoryReached()) {
140 Logger::warning('Memory limit reached, quitting.');
141 DI::lock()->release(self::LOCK_WORKER);
144 DI::lock()->release(self::LOCK_WORKER);
146 $last_check = time();
149 // Quit the worker once every cron interval
150 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
151 Logger::info('Process lifetime reached, respawning.');
152 self::unclaimProcess();
153 if (self::isDaemonMode()) {
154 self::IPCSetJobState(true);
163 $seconds = (time() - $start);
165 // logarithmic wait time calculation.
166 $arg = (($seconds + 1) / ($wait_interval / 9)) + 1;
167 $sleep = min(1000000, round(log10($arg) * 1000000, 0));
170 $timeout = ($seconds >= $wait_interval);
171 Logger::info('Timeout', ['timeout' => $timeout, 'seconds' => $seconds, 'sleep' => $sleep]);
174 if (DI::process()->isMaxLoadReached()) {
175 Logger::notice('maximum load reached, quitting.');
179 // Kill stale processes every 5 minutes
180 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
181 if (time() > ($last_cleanup + 300)) {
182 DI::config()->set('system', 'worker_last_cleaned', time());
183 self::killStaleWorkers();
186 // Check if the system is ready
187 if (!self::isReady()) {
193 // Cleaning up. Possibly not needed, but it doesn't harm anything.
194 if (self::isDaemonMode()) {
195 self::IPCSetJobState(false);
197 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
201 * Checks if the system is ready.
203 * Several system parameters like memory, connections and processes are checked.
207 public static function isReady()
209 // Count active workers and compare them with a maximum value that depends on the load
210 if (self::tooMuchWorkers()) {
211 Logger::notice('Active worker limit reached, quitting.');
215 // Do we have too few memory?
216 if (DI::process()->isMinMemoryReached()) {
217 Logger::warning('Memory limit reached, quitting.');
221 // Possibly there are too much database connections
222 if (self::maxConnectionsReached()) {
223 Logger::warning('Maximum connections reached, quitting.');
227 // Possibly there are too much database processes that block the system
228 if (DI::process()->isMaxProcessesReached()) {
229 Logger::warning('Maximum processes reached, quitting.');
237 * Check if non executed tasks do exist in the worker queue
239 * @return boolean Returns "true" if tasks are existing
242 public static function entriesExists()
244 $stamp = (float)microtime(true);
245 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
246 self::$db_duration += (microtime(true) - $stamp);
251 * Returns the number of deferred entries in the worker queue
253 * @return integer Number of deferred entries in the worker queue
256 private static function deferredEntries()
258 $stamp = (float)microtime(true);
259 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
260 self::$db_duration += (microtime(true) - $stamp);
261 self::$db_duration_count += (microtime(true) - $stamp);
266 * Returns the number of non executed entries in the worker queue
268 * @return integer Number of non executed entries in the worker queue
271 private static function totalEntries()
273 $stamp = (float)microtime(true);
274 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
275 self::$db_duration += (microtime(true) - $stamp);
276 self::$db_duration_count += (microtime(true) - $stamp);
281 * Returns the highest priority in the worker queue that isn't executed
283 * @return integer Number of active worker processes
286 private static function highestPriority()
288 $stamp = (float)microtime(true);
289 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
290 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
291 self::$db_duration += (microtime(true) - $stamp);
292 if (DBA::isResult($workerqueue)) {
293 return $workerqueue["priority"];
300 * Returns if a process with the given priority is running
302 * @param integer $priority The priority that should be checked
304 * @return integer Is there a process running with that priority?
307 private static function processWithPriorityActive($priority)
309 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
310 return DBA::exists('workerqueue', $condition);
314 * Execute a worker entry
316 * @param array $queue Workerqueue entry
318 * @return boolean "true" if further processing should be stopped
319 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 public static function execute($queue)
325 // Quit when in maintenance
326 if (DI::config()->get('system', 'maintenance', false, true)) {
327 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
331 // Constantly check the number of parallel database processes
332 if (DI::process()->isMaxProcessesReached()) {
333 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
337 // Constantly check the number of available database connections to let the frontend be accessible at any time
338 if (self::maxConnectionsReached()) {
339 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
343 $argv = json_decode($queue['parameter'], true);
344 if (!empty($queue['command'])) {
345 array_unshift($argv, $queue['command']);
349 Logger::warning('Parameter is empty', ['queue' => $queue]);
353 // Check for existance and validity of the include file
356 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
357 // We constantly update the "executed" date every minute to avoid being killed too soon
358 if (!isset(self::$last_update)) {
359 self::$last_update = strtotime($queue["executed"]);
362 $age = (time() - self::$last_update) / 60;
363 self::$last_update = time();
366 $stamp = (float)microtime(true);
367 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
368 self::$db_duration += (microtime(true) - $stamp);
369 self::$db_duration_write += (microtime(true) - $stamp);
374 self::execFunction($queue, $include, $argv, true);
376 $stamp = (float)microtime(true);
377 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
378 if (DBA::update('workerqueue', ['done' => true], $condition)) {
379 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
381 self::$db_duration = (microtime(true) - $stamp);
382 self::$db_duration_write += (microtime(true) - $stamp);
387 // The script could be provided as full path or only with the function name
388 if ($include == basename($include)) {
389 $include = "include/".$include.".php";
392 if (!validate_include($include)) {
393 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
394 $stamp = (float)microtime(true);
395 DBA::delete('workerqueue', ['id' => $queue["id"]]);
396 self::$db_duration = (microtime(true) - $stamp);
397 self::$db_duration_write += (microtime(true) - $stamp);
401 require_once $include;
403 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
405 if (function_exists($funcname)) {
406 // We constantly update the "executed" date every minute to avoid being killed too soon
407 if (!isset(self::$last_update)) {
408 self::$last_update = strtotime($queue["executed"]);
411 $age = (time() - self::$last_update) / 60;
412 self::$last_update = time();
415 $stamp = (float)microtime(true);
416 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
417 self::$db_duration += (microtime(true) - $stamp);
418 self::$db_duration_write += (microtime(true) - $stamp);
421 self::execFunction($queue, $funcname, $argv, false);
423 $stamp = (float)microtime(true);
424 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
425 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
427 self::$db_duration = (microtime(true) - $stamp);
428 self::$db_duration_write += (microtime(true) - $stamp);
430 Logger::warning("Function does not exist", ['function' => $funcname]);
431 $stamp = (float)microtime(true);
432 DBA::delete('workerqueue', ['id' => $queue["id"]]);
433 self::$db_duration = (microtime(true) - $stamp);
434 self::$db_duration_write += (microtime(true) - $stamp);
441 * Execute a function from the queue
443 * @param array $queue Workerqueue entry
444 * @param string $funcname name of the function
445 * @param array $argv Array of values to be passed to the function
446 * @param boolean $method_call boolean
448 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
450 private static function execFunction($queue, $funcname, $argv, $method_call)
454 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
456 Logger::info('Pre execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
460 Logger::enableWorker($funcname);
462 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
464 $stamp = (float)microtime(true);
466 // We use the callstack here to analyze the performance of executed worker entries.
467 // For this reason the variables have to be initialized.
468 DI::profiler()->reset();
470 if (!in_array($queue['priority'], PRIORITIES)) {
471 Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
472 $queue['priority'] = PRIORITY_MEDIUM;
477 $up_duration = microtime(true) - self::$up_start;
479 // Reset global data to avoid interferences
482 // Set the workerLogger as new default logger
484 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
486 $funcname($argv, count($argv));
489 Logger::disableWorker();
493 $duration = (microtime(true) - $stamp);
495 /* With these values we can analyze how effective the worker is.
496 * The database and rest time should be low since this is the unproductive time.
497 * The execution time is the productive time.
498 * By changing parameters like the maximum number of workers we can check the effectivness.
500 $dbtotal = round(self::$db_duration, 2);
501 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
502 $dbcount = round(self::$db_duration_count, 2);
503 $dbstat = round(self::$db_duration_stat, 2);
504 $dbwrite = round(self::$db_duration_write, 2);
505 $dblock = round(self::$lock_duration, 2);
506 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
507 $exec = round($duration, 2);
509 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
511 self::$up_start = microtime(true);
512 self::$db_duration = 0;
513 self::$db_duration_count = 0;
514 self::$db_duration_stat = 0;
515 self::$db_duration_write = 0;
516 self::$lock_duration = 0;
518 if ($duration > 3600) {
519 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
520 } elseif ($duration > 600) {
521 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
522 } elseif ($duration > 300) {
523 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
524 } elseif ($duration > 120) {
525 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
528 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
530 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
533 Logger::info('Post execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
539 * Checks if the number of database connections has reached a critical limit.
541 * @return bool Are more than 3/4 of the maximum connections used?
542 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
544 private static function maxConnectionsReached()
546 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
547 $max = DI::config()->get("system", "max_connections");
549 // Fetch the percentage level where the worker will get active
550 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
553 // the maximum number of possible user connections can be a system variable
554 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
555 if (DBA::isResult($r)) {
558 // Or it can be granted. This overrides the system variable
559 $stamp = (float)microtime(true);
560 $r = DBA::p('SHOW GRANTS');
561 self::$db_duration += (microtime(true) - $stamp);
562 while ($grants = DBA::fetch($r)) {
563 $grant = array_pop($grants);
564 if (stristr($grant, "GRANT USAGE ON")) {
565 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
573 // If $max is set we will use the processlist to determine the current number of connections
574 // The processlist only shows entries of the current user
576 $stamp = (float)microtime(true);
577 $r = DBA::p('SHOW PROCESSLIST');
578 self::$db_duration += (microtime(true) - $stamp);
579 $used = DBA::numRows($r);
582 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
584 $level = ($used / $max) * 100;
586 if ($level >= $maxlevel) {
587 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
592 // We will now check for the system values.
593 // This limit could be reached although the user limits are fine.
594 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
595 if (!DBA::isResult($r)) {
598 $max = intval($r["Value"]);
602 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
603 if (!DBA::isResult($r)) {
606 $used = intval($r["Value"]);
610 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
612 $level = $used / $max * 100;
614 if ($level < $maxlevel) {
617 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
622 * fix the queue entry if the worker process died
627 private static function killStaleWorkers()
629 $stamp = (float)microtime(true);
630 $entries = DBA::select(
632 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
633 ['NOT `done` AND `pid` != 0'],
634 ['order' => ['priority', 'retrial', 'created']]
636 self::$db_duration += (microtime(true) - $stamp);
638 while ($entry = DBA::fetch($entries)) {
639 if (!posix_kill($entry["pid"], 0)) {
640 $stamp = (float)microtime(true);
643 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
644 ['id' => $entry["id"]]
646 self::$db_duration += (microtime(true) - $stamp);
647 self::$db_duration_write += (microtime(true) - $stamp);
649 // Kill long running processes
650 // Check if the priority is in a valid range
651 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
652 $entry["priority"] = PRIORITY_MEDIUM;
655 // Define the maximum durations
656 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
657 $max_duration = $max_duration_defaults[$entry["priority"]];
659 $argv = json_decode($entry['parameter'], true);
660 if (!empty($entry['command'])) {
661 $command = $entry['command'];
662 } elseif (!empty($argv)) {
663 $command = array_shift($argv);
668 $command = basename($command);
670 // How long is the process already running?
671 $duration = (time() - strtotime($entry["executed"])) / 60;
672 if ($duration > $max_duration) {
673 Logger::notice('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
674 posix_kill($entry["pid"], SIGTERM);
676 // We killed the stale process.
677 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
678 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
679 $new_priority = $entry["priority"];
680 if ($entry["priority"] == PRIORITY_HIGH) {
681 $new_priority = PRIORITY_MEDIUM;
682 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
683 $new_priority = PRIORITY_LOW;
684 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
685 $new_priority = PRIORITY_NEGLIGIBLE;
687 $stamp = (float)microtime(true);
690 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
691 ['id' => $entry["id"]]
693 self::$db_duration += (microtime(true) - $stamp);
694 self::$db_duration_write += (microtime(true) - $stamp);
696 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
700 DBA::close($entries);
704 * Checks if the number of active workers exceeds the given limits
706 * @return bool Are there too much workers running?
707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
709 private static function tooMuchWorkers()
711 $queues = DI::config()->get("system", "worker_queues", 10);
713 $maxqueues = $queues;
715 $active = self::activeWorkers();
717 // Decrease the number of workers at higher load
718 $load = System::currentLoad();
720 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
722 /* Default exponent 3 causes queues to rapidly decrease as load increases.
723 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
724 * For some environments, this rapid decrease is not needed.
725 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
727 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
728 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
729 $queues = intval(ceil($slope * $maxqueues));
733 if (DI::config()->get('system', 'worker_jpm')) {
734 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
735 $jobs_per_minute = [];
736 foreach ($intervals as $interval) {
737 if ($interval == 0) {
740 $interval = (int)$interval;
743 $stamp = (float)microtime(true);
744 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
745 self::$db_duration += (microtime(true) - $stamp);
746 self::$db_duration_stat += (microtime(true) - $stamp);
747 if ($job = DBA::fetch($jobs)) {
748 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
752 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
755 // Create a list of queue entries grouped by their priority
756 $listitem = [0 => ''];
758 $idle_workers = $active;
760 $deferred = self::deferredEntries();
762 if (DI::config()->get('system', 'worker_debug')) {
763 $waiting_processes = 0;
764 // Now adding all processes with workerqueue entries
765 $stamp = (float)microtime(true);
766 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
767 self::$db_duration += (microtime(true) - $stamp);
768 self::$db_duration_stat += (microtime(true) - $stamp);
769 while ($entry = DBA::fetch($jobs)) {
770 $stamp = (float)microtime(true);
771 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
772 self::$db_duration += (microtime(true) - $stamp);
773 self::$db_duration_stat += (microtime(true) - $stamp);
774 if ($process = DBA::fetch($processes)) {
775 $idle_workers -= $process["running"];
776 $waiting_processes += $entry["entries"];
777 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
779 DBA::close($processes);
783 $waiting_processes = self::totalEntries();
784 $stamp = (float)microtime(true);
785 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
786 self::$db_duration += (microtime(true) - $stamp);
787 self::$db_duration_stat += (microtime(true) - $stamp);
789 while ($entry = DBA::fetch($jobs)) {
790 $idle_workers -= $entry["running"];
791 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
796 $waiting_processes -= $deferred;
798 $listitem[0] = "0:" . max(0, $idle_workers);
800 $processlist .= ' ('.implode(', ', $listitem).')';
802 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
803 $top_priority = self::highestPriority();
804 $high_running = self::processWithPriorityActive($top_priority);
806 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
807 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
808 $queues = $active + 1;
812 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
814 // Are there fewer workers running as possible? Then fork a new one.
815 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
816 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
817 if (self::isDaemonMode()) {
818 self::IPCSetJobState(true);
825 // if there are too much worker, we don't spawn a new one.
826 if (self::isDaemonMode() && ($active > $queues)) {
827 self::IPCSetJobState(false);
830 return $active > $queues;
834 * Returns the number of active worker processes
836 * @return integer Number of active worker processes
839 private static function activeWorkers()
841 $stamp = (float)microtime(true);
842 $count = DBA::count('process', ['command' => 'Worker.php']);
843 self::$db_duration += (microtime(true) - $stamp);
844 self::$db_duration_count += (microtime(true) - $stamp);
849 * Returns the number of active worker processes
851 * @return array List of worker process ids
854 private static function getWorkerPIDList()
857 $stamp = (float)microtime(true);
859 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
860 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
861 GROUP BY `process`.`pid`");
862 while ($queue = DBA::fetch($queues)) {
863 $ids[$queue['pid']] = $queue['entries'];
867 self::$db_duration += (microtime(true) - $stamp);
868 self::$db_duration_count += (microtime(true) - $stamp);
873 * Returns waiting jobs for the current process id
875 * @return array waiting workerqueue jobs
878 private static function getWaitingJobForPID()
880 $stamp = (float)microtime(true);
881 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
882 self::$db_duration += (microtime(true) - $stamp);
883 if (DBA::isResult($r)) {
884 return DBA::toArray($r);
892 * Returns the next jobs that should be executed
894 * @return array array with next jobs
897 private static function nextProcess(int $limit)
899 $priority = self::nextPriority();
900 if (empty($priority)) {
901 Logger::info('No tasks found');
906 $stamp = (float)microtime(true);
907 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
908 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
909 self::$db_duration += (microtime(true) - $stamp);
910 while ($task = DBA::fetch($tasks)) {
911 $ids[] = $task['id'];
912 // Only continue that loop while we are storing commands that can be processed quickly
913 if (!empty($task['command'])) {
914 $command = $task['command'];
916 $command = json_decode($task['parameter'])[0];
919 if (!in_array($command, self::FAST_COMMANDS)) {
925 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
930 * Returns the priority of the next workerqueue job
932 * @return string priority
935 private static function nextPriority()
938 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
939 foreach ($priorities as $priority) {
940 $stamp = (float)microtime(true);
941 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
942 $waiting[$priority] = true;
944 self::$db_duration += (microtime(true) - $stamp);
947 if (!empty($waiting[PRIORITY_CRITICAL])) {
948 return PRIORITY_CRITICAL;
953 $stamp = (float)microtime(true);
954 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
955 self::$db_duration += (microtime(true) - $stamp);
956 while ($process = DBA::fetch($processes)) {
957 $running[$process['priority']] = $process['running'];
958 $running_total += $process['running'];
960 DBA::close($processes);
962 foreach ($priorities as $priority) {
963 if (!empty($waiting[$priority]) && empty($running[$priority])) {
964 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
969 $active = max(self::activeWorkers(), $running_total);
970 $priorities = max(count($waiting), count($running));
974 for ($i = 1; $i <= $priorities; ++$i) {
975 $total += pow($i, $exponent);
979 for ($i = 1; $i <= $priorities; ++$i) {
980 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
984 foreach ($running as $priority => $workers) {
985 if ($workers < $limit[$i++]) {
986 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
991 if (!empty($waiting)) {
992 $priority = array_keys($waiting)[0];
993 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
1001 * Find and claim the next worker process for us
1003 * @return boolean Have we found something?
1004 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1006 private static function findWorkerProcesses()
1008 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
1010 if (DI::config()->get('system', 'worker_multiple_fetch')) {
1012 foreach (self::getWorkerPIDList() as $pid => $count) {
1013 if ($count <= $fetch_limit) {
1020 $limit = $fetch_limit * count($pids);
1022 $pids = [getmypid()];
1023 $limit = $fetch_limit;
1026 $ids = self::nextProcess($limit);
1027 $limit -= count($ids);
1029 // If there is not enough results we check without priority limit
1031 $stamp = (float)microtime(true);
1032 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
1033 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1034 self::$db_duration += (microtime(true) - $stamp);
1036 while ($task = DBA::fetch($tasks)) {
1037 $ids[] = $task['id'];
1038 // Only continue that loop while we are storing commands that can be processed quickly
1039 if (!empty($task['command'])) {
1040 $command = $task['command'];
1042 $command = json_decode($task['parameter'])[0];
1044 if (!in_array($command, self::FAST_COMMANDS)) {
1055 // Assign the task ids to the workers
1057 foreach (array_unique($ids) as $id) {
1060 $pid = reset($pids);
1062 $worker[$pid][] = $id;
1065 $stamp = (float)microtime(true);
1066 foreach ($worker as $worker_pid => $worker_ids) {
1067 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1068 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1069 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1071 self::$db_duration += (microtime(true) - $stamp);
1072 self::$db_duration_write += (microtime(true) - $stamp);
1076 * Returns the next worker process
1078 * @return array worker processes
1079 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1081 public static function workerProcess()
1083 // There can already be jobs for us in the queue.
1084 $waiting = self::getWaitingJobForPID();
1085 if (!empty($waiting)) {
1089 $stamp = (float)microtime(true);
1090 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1093 self::$lock_duration += (microtime(true) - $stamp);
1095 self::findWorkerProcesses();
1097 DI::lock()->release(self::LOCK_PROCESS);
1099 return self::getWaitingJobForPID();
1103 * Removes a workerqueue entry from the current process
1106 * @throws \Exception
1108 public static function unclaimProcess()
1110 $mypid = getmypid();
1112 $stamp = (float)microtime(true);
1113 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1114 self::$db_duration += (microtime(true) - $stamp);
1115 self::$db_duration_write += (microtime(true) - $stamp);
1119 * Call the front end worker
1122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1124 public static function callWorker()
1126 if (!DI::config()->get("system", "frontend_worker")) {
1130 $url = DI::baseUrl() . '/worker';
1131 DI::httpRequest()->fetch($url, 1);
1135 * Call the front end worker if there aren't any active
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 public static function executeIfIdle()
1142 self::checkDaemonState();
1144 if (!DI::config()->get("system", "frontend_worker")) {
1148 // Do we have "proc_open"? Then we can fork the worker
1149 if (function_exists("proc_open")) {
1150 // When was the last time that we called the worker?
1151 // Less than one minute? Then we quit
1152 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1156 DI::config()->set("system", "worker_started", time());
1158 // Do we have enough running workers? Then we quit here.
1159 if (self::tooMuchWorkers()) {
1160 // Cleaning dead processes
1161 self::killStaleWorkers();
1162 DI::modelProcess()->deleteInactive();
1169 Logger::info('Call worker');
1170 self::spawnWorker();
1174 // We cannot execute background processes.
1175 // We now run the processes from the frontend.
1176 // This won't work with long running processes.
1179 self::clearProcesses();
1181 $workers = self::activeWorkers();
1183 if ($workers == 0) {
1189 * Removes long running worker processes
1192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1194 public static function clearProcesses()
1196 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1198 /// @todo We should clean up the corresponding workerqueue entries as well
1199 $stamp = (float)microtime(true);
1200 $condition = ["`created` < ? AND `command` = 'worker.php'",
1201 DateTimeFormat::utc("now - ".$timeout." minutes")];
1202 DBA::delete('process', $condition);
1203 self::$db_duration = (microtime(true) - $stamp);
1204 self::$db_duration_write += (microtime(true) - $stamp);
1208 * Runs the cron processes
1211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1213 private static function runCron()
1215 Logger::info('Add cron entries');
1217 // Check for spooled items
1218 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1220 // Run the cron job that calls all other jobs
1221 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1223 // Cleaning dead processes
1224 self::killStaleWorkers();
1228 * Fork a child process
1230 * @param boolean $do_cron
1233 private static function forkProcess(bool $do_cron)
1235 if (DI::process()->isMinMemoryReached()) {
1236 Logger::warning('Memory limit reached - quitting');
1240 // Children inherit their parent's database connection.
1241 // To avoid problems we disconnect and connect both parent and child
1243 $pid = pcntl_fork();
1246 Logger::warning('Could not spawn worker');
1249 // The parent process continues here
1251 Logger::info('Spawned new worker', ['cron' => $do_cron, 'pid' => $pid]);
1255 // We now are in the new worker
1257 Logger::info('Worker spawned', ['cron' => $do_cron, 'pid' => getmypid()]);
1259 DI::process()->start();
1261 self::processQueue($do_cron);
1263 self::unclaimProcess();
1265 DI::process()->end();
1266 Logger::info('Worker ended', ['cron' => $do_cron, 'pid' => getmypid()]);
1270 $php = '/usr/bin/php';
1271 $param = ['bin/worker.php'];
1273 $param[] = 'no_cron';
1275 pcntl_exec($php, $param);
1276 Logger::warning('Error calling worker', ['cron' => $do_cron, 'pid' => getmypid()]);
1282 * Spawns a new worker
1284 * @param bool $do_cron
1286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1288 public static function spawnWorker($do_cron = false)
1290 if (self::isDaemonMode()) {
1291 self::forkProcess($do_cron);
1292 self::IPCSetJobState(false);
1294 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1295 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1296 $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1301 * Adds tasks to the worker queue
1303 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1305 * next args are passed as $cmd command line
1306 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1307 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1309 * @return boolean "false" if worker queue entry already existed or there had been an error
1310 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1311 * @note $cmd and string args are surrounded with ""
1317 public static function add($cmd)
1319 $args = func_get_args();
1321 if (!count($args)) {
1325 $arr = ['args' => $args, 'run_cmd' => true];
1327 Hook::callAll("proc_run", $arr);
1328 if (!$arr['run_cmd'] || !count($args)) {
1332 $priority = PRIORITY_MEDIUM;
1333 // Don't fork from frontend tasks by default
1334 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1335 $created = DateTimeFormat::utcNow();
1336 $delayed = DBA::NULL_DATETIME;
1337 $force_priority = false;
1339 $run_parameter = array_shift($args);
1341 if (is_int($run_parameter)) {
1342 $priority = $run_parameter;
1343 } elseif (is_array($run_parameter)) {
1344 if (isset($run_parameter['delayed'])) {
1345 $delayed = $run_parameter['delayed'];
1347 if (isset($run_parameter['priority'])) {
1348 $priority = $run_parameter['priority'];
1350 if (isset($run_parameter['created'])) {
1351 $created = $run_parameter['created'];
1353 if (isset($run_parameter['dont_fork'])) {
1354 $dont_fork = $run_parameter['dont_fork'];
1356 if (isset($run_parameter['force_priority'])) {
1357 $force_priority = $run_parameter['force_priority'];
1361 $command = array_shift($args);
1362 $parameters = json_encode($args);
1363 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1366 if (!in_array($priority, PRIORITIES)) {
1367 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1368 $priority = PRIORITY_MEDIUM;
1371 // Quit if there was a database error - a precaution for the update process to 3.5.3
1372 if (DBA::errorNo() != 0) {
1377 $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1378 'priority' => $priority, 'next_try' => $delayed]);
1382 } elseif ($force_priority) {
1383 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1386 // Set the IPC flag to ensure an immediate process execution via daemon
1387 if (self::isDaemonMode()) {
1388 self::IPCSetJobState(true);
1391 self::checkDaemonState();
1393 // Should we quit and wait for the worker to be called as a cronjob?
1398 // If there is a lock then we don't have to check for too much worker
1399 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1403 // If there are already enough workers running, don't fork another one
1404 $quit = self::tooMuchWorkers();
1405 DI::lock()->release(self::LOCK_WORKER);
1411 // Quit on daemon mode
1412 if (self::isDaemonMode()) {
1416 // Now call the worker to execute the jobs that we just added to the queue
1417 self::spawnWorker();
1422 public static function countWorkersByCommand(string $command)
1424 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1428 * Returns the next retrial level for worker jobs.
1429 * This function will skip levels when jobs are older.
1431 * @param array $queue Worker queue entry
1432 * @param integer $max_level maximum retrial level
1433 * @return integer the next retrial level value
1435 private static function getNextRetrial($queue, $max_level)
1437 $created = strtotime($queue['created']);
1438 $retrial_time = time() - $created;
1440 $new_retrial = $queue['retrial'] + 1;
1442 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1443 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1445 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1446 $new_retrial = $retrial;
1449 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1450 return $new_retrial;
1454 * Defers the current worker entry
1456 * @return boolean had the entry been deferred?
1458 public static function defer()
1460 if (empty(DI::app()->queue)) {
1464 $queue = DI::app()->queue;
1466 $retrial = $queue['retrial'];
1468 $priority = $queue['priority'];
1470 $max_level = DI::config()->get('system', 'worker_defer_limit');
1472 $new_retrial = self::getNextRetrial($queue, $max_level);
1474 if ($new_retrial > $max_level) {
1475 Logger::notice('The task exceeded the maximum retry count', ['id' => $id, 'created' => $queue['created'], 'old_prio' => $queue['priority'], 'old_retrial' => $queue['retrial'], 'max_level' => $max_level, 'retrial' => $new_retrial]);
1479 // Calculate the delay until the next trial
1480 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1481 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1483 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1484 $priority = PRIORITY_MEDIUM;
1485 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1486 $priority = PRIORITY_LOW;
1487 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1488 $priority = PRIORITY_NEGLIGIBLE;
1491 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1493 $stamp = (float)microtime(true);
1494 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1495 DBA::update('workerqueue', $fields, ['id' => $id]);
1496 self::$db_duration += (microtime(true) - $stamp);
1497 self::$db_duration_write += (microtime(true) - $stamp);
1503 * Set the flag if some job is waiting
1505 * @param boolean $jobs Is there a waiting job?
1506 * @throws \Exception
1508 public static function IPCSetJobState($jobs)
1510 $stamp = (float)microtime(true);
1511 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1512 self::$db_duration += (microtime(true) - $stamp);
1513 self::$db_duration_write += (microtime(true) - $stamp);
1517 * Checks if some worker job waits to be executed
1520 * @throws \Exception
1522 public static function IPCJobsExists()
1524 $stamp = (float)microtime(true);
1525 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1526 self::$db_duration += (microtime(true) - $stamp);
1528 // When we don't have a row, no job is running
1529 if (!DBA::isResult($row)) {
1533 return (bool)$row['jobs'];
1537 * Checks if the worker is running in the daemon mode.
1541 public static function isDaemonMode()
1543 if (!is_null(self::$daemon_mode)) {
1544 return self::$daemon_mode;
1547 if (DI::mode()->getExecutor() == Mode::DAEMON) {
1551 $daemon_mode = DI::config()->get('system', 'worker_daemon_mode', false, true);
1553 return $daemon_mode;
1556 if (!function_exists('pcntl_fork')) {
1557 self::$daemon_mode = false;
1561 $pidfile = DI::config()->get('system', 'pidfile');
1562 if (empty($pidfile)) {
1563 // No pid file, no daemon
1564 self::$daemon_mode = false;
1568 if (!is_readable($pidfile)) {
1569 // No pid file. We assume that the daemon had been intentionally stopped.
1570 self::$daemon_mode = false;
1574 $pid = intval(file_get_contents($pidfile));
1575 $running = posix_kill($pid, 0);
1577 self::$daemon_mode = $running;
1582 * Test if the daemon is running. If not, it will be started
1586 private static function checkDaemonState()
1588 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1592 if (!DI::mode()->isNormal()) {
1596 // Check every minute if the daemon is running
1597 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1601 DI::config()->set('system', 'last_daemon_check', time());
1603 $pidfile = DI::config()->get('system', 'pidfile');
1604 if (empty($pidfile)) {
1605 // No pid file, no daemon
1609 if (!is_readable($pidfile)) {
1610 // No pid file. We assume that the daemon had been intentionally stopped.
1614 $pid = intval(file_get_contents($pidfile));
1615 if (posix_kill($pid, 0)) {
1616 Logger::info('Daemon process is running', ['pid' => $pid]);
1620 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1622 self::spawnDaemon();
1626 * Spawn a new daemon process
1630 private static function spawnDaemon()
1632 Logger::notice('Starting new daemon process');
1633 $command = 'bin/daemon.php';
1635 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1636 $process->run($command, ['start']);
1637 Logger::notice('New daemon process started');
1641 * Check if the system is inside the defined maintenance window
1645 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1647 // Calculate the seconds of the start end end of the maintenance window
1648 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1649 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1651 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1653 if ($check_last_execution) {
1654 // Calculate the window duration
1655 $duration = max($start, $end) - min($start, $end);
1657 // Quit when the last cron execution had been after the previous window
1658 $last_cron = DI::config()->get('system', 'last_cron_daily');
1659 if ($last_cron + $duration > time()) {
1660 Logger::info('The Daily cron had been executed recently', ['last' => date(DateTimeFormat::MYSQL, $last_cron), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1665 $current = time() % 86400;
1667 if ($start < $end) {
1668 // Execute if we are inside the window
1669 $execute = ($current >= $start) && ($current <= $end);
1671 // Don't execute if we are outside the window
1672 $execute = !(($current > $end) && ($current < $start));
1676 Logger::info('We are inside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1678 Logger::info('We are outside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);