3 * @copyright Copyright (C) 2010-2022, the Friendica project
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;
25 use Friendica\Core\Worker\Entity\Process;
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;
55 private static $process;
58 * Processes the tasks that are in the workerqueue table
60 * @param boolean $run_cron Should the cron processes be executed?
61 * @param Process $process The current running process
63 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
65 public static function processQueue($run_cron, Process $process)
67 self::$up_start = microtime(true);
69 // At first check the maximum load. We shouldn't continue with a high load
70 if (DI::system()->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 self::$process = $process;
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;
98 // We fetch the next queue entry that is about to be executed
99 while ($r = self::workerProcess()) {
100 if (self::IPCJobsExists(getmypid())) {
101 self::IPCDeleteJobState(getmypid());
104 // Don't refetch when a worker fetches tasks for multiple workers
105 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
106 foreach ($r as $entry) {
107 $entry = self::checkPriority($entry);
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::system()->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($process);
153 if (self::isDaemonMode()) {
154 self::IPCSetJobState(true);
162 // Cleaning up. Possibly not needed, but it doesn't harm anything.
163 if (self::isDaemonMode()) {
164 self::IPCSetJobState(false);
166 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
170 * Check and fix the priority of a worker task
171 * @param array $entry
174 private static function checkPriority(array $entry)
176 $entry['priority'] = (int)$entry['priority'];
178 if (!in_array($entry['priority'], PRIORITIES)) {
179 Logger::warning('Invalid priority', ['entry' => $entry, 'callstack' => System::callstack(20)]);
180 DBA::update('workerqueue', ['priority' => PRIORITY_MEDIUM], ['id' => $entry['id']]);
181 $entry['priority'] = PRIORITY_MEDIUM;
188 * Checks if the system is ready.
190 * Several system parameters like memory, connections and processes are checked.
194 public static function isReady()
196 // Count active workers and compare them with a maximum value that depends on the load
197 if (self::tooMuchWorkers()) {
198 Logger::notice('Active worker limit reached, quitting.');
202 // Do we have too few memory?
203 if (DI::system()->isMinMemoryReached()) {
204 Logger::warning('Memory limit reached, quitting.');
208 // Possibly there are too much database connections
209 if (self::maxConnectionsReached()) {
210 Logger::warning('Maximum connections reached, quitting.');
214 // Possibly there are too much database processes that block the system
215 if (DI::system()->isMaxProcessesReached()) {
216 Logger::warning('Maximum processes reached, quitting.');
224 * Check if non executed tasks do exist in the worker queue
226 * @return boolean Returns "true" if tasks are existing
229 public static function entriesExists()
231 $stamp = (float)microtime(true);
232 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
233 self::$db_duration += (microtime(true) - $stamp);
238 * Returns the number of deferred entries in the worker queue
240 * @return integer Number of deferred entries in the worker queue
243 private static function deferredEntries()
245 $stamp = (float)microtime(true);
246 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
247 self::$db_duration += (microtime(true) - $stamp);
248 self::$db_duration_count += (microtime(true) - $stamp);
253 * Returns the number of non executed entries in the worker queue
255 * @return integer Number of non executed entries in the worker queue
258 private static function totalEntries()
260 $stamp = (float)microtime(true);
261 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
262 self::$db_duration += (microtime(true) - $stamp);
263 self::$db_duration_count += (microtime(true) - $stamp);
268 * Returns the highest priority in the worker queue that isn't executed
270 * @return integer Number of active worker processes
273 private static function highestPriority()
275 $stamp = (float)microtime(true);
276 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
277 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
278 self::$db_duration += (microtime(true) - $stamp);
279 if (DBA::isResult($workerqueue)) {
280 return $workerqueue['priority'];
287 * Returns if a process with the given priority is running
289 * @param integer $priority The priority that should be checked
291 * @return integer Is there a process running with that priority?
294 private static function processWithPriorityActive($priority)
296 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
297 return DBA::exists('workerqueue', $condition);
301 * Checks if the given file is valid to be included
306 private static function validateInclude(&$file)
310 $file = realpath($file);
312 if (strpos($file, getcwd()) !== 0) {
316 $file = str_replace(getcwd() . "/", "", $file, $count);
321 if ($orig_file !== $file) {
326 if (strpos($file, "include/") === 0) {
330 if (strpos($file, "addon/") === 0) {
334 // Simply return flag
339 * Execute a worker entry
341 * @param array $queue Workerqueue entry
343 * @return boolean "true" if further processing should be stopped
344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
346 public static function execute($queue)
350 // Quit when in maintenance
351 if (DI::config()->get('system', 'maintenance', false, true)) {
352 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
356 // Constantly check the number of parallel database processes
357 if (DI::system()->isMaxProcessesReached()) {
358 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
362 // Constantly check the number of available database connections to let the frontend be accessible at any time
363 if (self::maxConnectionsReached()) {
364 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
368 $argv = json_decode($queue['parameter'], true);
369 if (!is_array($argv)) {
373 if (!empty($queue['command'])) {
374 array_unshift($argv, $queue['command']);
378 Logger::warning('Parameter is empty', ['queue' => $queue]);
382 // Check for existance and validity of the include file
385 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
386 // We constantly update the "executed" date every minute to avoid being killed too soon
387 if (!isset(self::$last_update)) {
388 self::$last_update = strtotime($queue["executed"]);
391 $age = (time() - self::$last_update) / 60;
392 self::$last_update = time();
395 $stamp = (float)microtime(true);
396 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
397 self::$db_duration += (microtime(true) - $stamp);
398 self::$db_duration_write += (microtime(true) - $stamp);
403 self::execFunction($queue, $include, $argv, true);
405 $stamp = (float)microtime(true);
406 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
407 if (DBA::update('workerqueue', ['done' => true], $condition)) {
408 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
410 self::$db_duration = (microtime(true) - $stamp);
411 self::$db_duration_write += (microtime(true) - $stamp);
416 // The script could be provided as full path or only with the function name
417 if ($include == basename($include)) {
418 $include = "include/".$include.".php";
421 if (!self::validateInclude($include)) {
422 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
423 $stamp = (float)microtime(true);
424 DBA::delete('workerqueue', ['id' => $queue["id"]]);
425 self::$db_duration = (microtime(true) - $stamp);
426 self::$db_duration_write += (microtime(true) - $stamp);
430 require_once $include;
432 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
434 if (function_exists($funcname)) {
435 // We constantly update the "executed" date every minute to avoid being killed too soon
436 if (!isset(self::$last_update)) {
437 self::$last_update = strtotime($queue["executed"]);
440 $age = (time() - self::$last_update) / 60;
441 self::$last_update = time();
444 $stamp = (float)microtime(true);
445 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
446 self::$db_duration += (microtime(true) - $stamp);
447 self::$db_duration_write += (microtime(true) - $stamp);
450 self::execFunction($queue, $funcname, $argv, false);
452 $stamp = (float)microtime(true);
453 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
454 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
456 self::$db_duration = (microtime(true) - $stamp);
457 self::$db_duration_write += (microtime(true) - $stamp);
459 Logger::warning("Function does not exist", ['function' => $funcname]);
460 $stamp = (float)microtime(true);
461 DBA::delete('workerqueue', ['id' => $queue["id"]]);
462 self::$db_duration = (microtime(true) - $stamp);
463 self::$db_duration_write += (microtime(true) - $stamp);
470 * Execute a function from the queue
472 * @param array $queue Workerqueue entry
473 * @param string $funcname name of the function
474 * @param array $argv Array of values to be passed to the function
475 * @param boolean $method_call boolean
477 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
479 private static function execFunction($queue, $funcname, $argv, $method_call)
483 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
485 Logger::info('Pre execution cooldown.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'cooldown' => $cooldown]);
489 Logger::enableWorker($funcname);
491 Logger::info("Process start.", ['priority' => $queue['priority'], 'id' => $queue["id"]]);
493 $stamp = (float)microtime(true);
495 // We use the callstack here to analyze the performance of executed worker entries.
496 // For this reason the variables have to be initialized.
497 DI::profiler()->reset();
499 $a->setQueue($queue);
501 $up_duration = microtime(true) - self::$up_start;
503 // Reset global data to avoid interferences
506 // Set the workerLogger as new default logger
508 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
510 $funcname($argv, count($argv));
513 Logger::disableWorker();
517 $duration = (microtime(true) - $stamp);
519 /* With these values we can analyze how effective the worker is.
520 * The database and rest time should be low since this is the unproductive time.
521 * The execution time is the productive time.
522 * By changing parameters like the maximum number of workers we can check the effectivness.
524 $dbtotal = round(self::$db_duration, 2);
525 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
526 $dbcount = round(self::$db_duration_count, 2);
527 $dbstat = round(self::$db_duration_stat, 2);
528 $dbwrite = round(self::$db_duration_write, 2);
529 $dblock = round(self::$lock_duration, 2);
530 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
531 $exec = round($duration, 2);
533 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
535 self::$up_start = microtime(true);
536 self::$db_duration = 0;
537 self::$db_duration_count = 0;
538 self::$db_duration_stat = 0;
539 self::$db_duration_write = 0;
540 self::$lock_duration = 0;
542 if ($duration > 3600) {
543 Logger::info('Longer than 1 hour.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
544 } elseif ($duration > 600) {
545 Logger::info('Longer than 10 minutes.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
546 } elseif ($duration > 300) {
547 Logger::info('Longer than 5 minutes.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
548 } elseif ($duration > 120) {
549 Logger::info('Longer than 2 minutes.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
552 Logger::info('Process done.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
554 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
557 Logger::info('Post execution cooldown.', ['priority' => $queue['priority'], 'id' => $queue["id"], 'cooldown' => $cooldown]);
563 * Checks if the number of database connections has reached a critical limit.
565 * @return bool Are more than 3/4 of the maximum connections used?
566 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
568 private static function maxConnectionsReached()
570 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
571 $max = DI::config()->get("system", "max_connections");
573 // Fetch the percentage level where the worker will get active
574 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
577 // the maximum number of possible user connections can be a system variable
578 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
579 if (DBA::isResult($r)) {
582 // Or it can be granted. This overrides the system variable
583 $stamp = (float)microtime(true);
584 $r = DBA::p('SHOW GRANTS');
585 self::$db_duration += (microtime(true) - $stamp);
586 while ($grants = DBA::fetch($r)) {
587 $grant = array_pop($grants);
588 if (stristr($grant, "GRANT USAGE ON")) {
589 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
597 // If $max is set we will use the processlist to determine the current number of connections
598 // The processlist only shows entries of the current user
600 $stamp = (float)microtime(true);
601 $r = DBA::p('SHOW PROCESSLIST');
602 self::$db_duration += (microtime(true) - $stamp);
603 $used = DBA::numRows($r);
606 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
608 $level = ($used / $max) * 100;
610 if ($level >= $maxlevel) {
611 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
616 // We will now check for the system values.
617 // This limit could be reached although the user limits are fine.
618 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
619 if (!DBA::isResult($r)) {
622 $max = intval($r["Value"]);
626 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
627 if (!DBA::isResult($r)) {
630 $used = intval($r["Value"]);
634 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
636 $level = $used / $max * 100;
638 if ($level < $maxlevel) {
641 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
646 * fix the queue entry if the worker process died
651 private static function killStaleWorkers()
653 $stamp = (float)microtime(true);
654 $entries = DBA::select(
656 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
657 ['NOT `done` AND `pid` != 0'],
658 ['order' => ['priority', 'retrial', 'created']]
660 self::$db_duration += (microtime(true) - $stamp);
662 while ($entry = DBA::fetch($entries)) {
663 $entry = self::checkPriority($entry);
665 if (!posix_kill($entry["pid"], 0)) {
666 $stamp = (float)microtime(true);
669 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
670 ['id' => $entry["id"]]
672 self::$db_duration += (microtime(true) - $stamp);
673 self::$db_duration_write += (microtime(true) - $stamp);
675 // Kill long running processes
677 // Define the maximum durations
678 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
679 $max_duration = $max_duration_defaults[$entry['priority']];
681 $argv = json_decode($entry['parameter'], true);
682 if (!empty($entry['command'])) {
683 $command = $entry['command'];
684 } elseif (!empty($argv)) {
685 $command = array_shift($argv);
690 $command = basename($command);
692 // How long is the process already running?
693 $duration = (time() - strtotime($entry["executed"])) / 60;
694 if ($duration > $max_duration) {
695 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]);
696 posix_kill($entry["pid"], SIGTERM);
698 // We killed the stale process.
699 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
700 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
701 $new_priority = $entry['priority'];
702 if ($entry['priority'] == PRIORITY_HIGH) {
703 $new_priority = PRIORITY_MEDIUM;
704 } elseif ($entry['priority'] == PRIORITY_MEDIUM) {
705 $new_priority = PRIORITY_LOW;
706 } elseif ($entry['priority'] != PRIORITY_CRITICAL) {
707 $new_priority = PRIORITY_NEGLIGIBLE;
709 $stamp = (float)microtime(true);
712 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
713 ['id' => $entry["id"]]
715 self::$db_duration += (microtime(true) - $stamp);
716 self::$db_duration_write += (microtime(true) - $stamp);
718 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
722 DBA::close($entries);
726 * Checks if the number of active workers exceeds the given limits
728 * @return bool Are there too much workers running?
729 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
731 private static function tooMuchWorkers()
733 $queues = DI::config()->get("system", "worker_queues", 10);
735 $maxqueues = $queues;
737 $active = self::activeWorkers();
739 // Decrease the number of workers at higher load
740 $load = System::currentLoad();
742 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
744 /* Default exponent 3 causes queues to rapidly decrease as load increases.
745 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
746 * For some environments, this rapid decrease is not needed.
747 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
749 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
750 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
751 $queues = intval(ceil($slope * $maxqueues));
755 if (DI::config()->get('system', 'worker_jpm')) {
756 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
757 $jobs_per_minute = [];
758 foreach ($intervals as $interval) {
759 if ($interval == 0) {
762 $interval = (int)$interval;
765 $stamp = (float)microtime(true);
766 $jobs = DBA::count('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $interval . ' minute')]);
767 self::$db_duration += (microtime(true) - $stamp);
768 self::$db_duration_stat += (microtime(true) - $stamp);
769 $jobs_per_minute[$interval] = number_format($jobs / $interval, 0);
771 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
774 // Create a list of queue entries grouped by their priority
775 $listitem = [0 => ''];
777 $idle_workers = $active;
779 $deferred = self::deferredEntries();
781 if (DI::config()->get('system', 'worker_debug')) {
782 $waiting_processes = 0;
783 // Now adding all processes with workerqueue entries
784 $stamp = (float)microtime(true);
785 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
786 self::$db_duration += (microtime(true) - $stamp);
787 self::$db_duration_stat += (microtime(true) - $stamp);
788 while ($entry = DBA::fetch($jobs)) {
789 $stamp = (float)microtime(true);
790 $running = DBA::count('workerqueue-view', ['priority' => $entry['priority']]);
791 self::$db_duration += (microtime(true) - $stamp);
792 self::$db_duration_stat += (microtime(true) - $stamp);
793 $idle_workers -= $running;
794 $waiting_processes += $entry["entries"];
795 $listitem[$entry['priority']] = $entry['priority'] . ":" . $running . "/" . $entry["entries"];
799 $waiting_processes = self::totalEntries();
800 $stamp = (float)microtime(true);
801 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
802 self::$db_duration += (microtime(true) - $stamp);
803 self::$db_duration_stat += (microtime(true) - $stamp);
805 while ($entry = DBA::fetch($jobs)) {
806 $idle_workers -= $entry["running"];
807 $listitem[$entry['priority']] = $entry['priority'].":".$entry["running"];
812 $waiting_processes -= $deferred;
814 $listitem[0] = "0:" . max(0, $idle_workers);
816 $processlist .= ' ('.implode(', ', $listitem).')';
818 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
819 $top_priority = self::highestPriority();
820 $high_running = self::processWithPriorityActive($top_priority);
822 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
823 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
824 $queues = $active + 1;
828 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
830 // Are there fewer workers running as possible? Then fork a new one.
831 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
832 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
833 if (self::isDaemonMode()) {
834 self::IPCSetJobState(true);
841 // if there are too much worker, we don't spawn a new one.
842 if (self::isDaemonMode() && ($active > $queues)) {
843 self::IPCSetJobState(false);
846 return $active > $queues;
850 * Returns the number of active worker processes
852 * @return integer Number of active worker processes
855 private static function activeWorkers()
857 $stamp = (float)microtime(true);
858 $count = DI::process()->countCommand('Worker.php');
859 self::$db_duration += (microtime(true) - $stamp);
860 self::$db_duration_count += (microtime(true) - $stamp);
865 * Returns the number of active worker processes
867 * @return array List of worker process ids
870 private static function getWorkerPIDList()
873 $stamp = (float)microtime(true);
875 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
876 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
877 GROUP BY `process`.`pid`");
878 while ($queue = DBA::fetch($queues)) {
879 $ids[$queue['pid']] = $queue['entries'];
883 self::$db_duration += (microtime(true) - $stamp);
884 self::$db_duration_count += (microtime(true) - $stamp);
889 * Returns waiting jobs for the current process id
891 * @return array waiting workerqueue jobs
894 private static function getWaitingJobForPID()
896 $stamp = (float)microtime(true);
897 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
898 self::$db_duration += (microtime(true) - $stamp);
899 if (DBA::isResult($r)) {
900 return DBA::toArray($r);
908 * Returns the next jobs that should be executed
910 * @return array array with next jobs
913 private static function nextProcess(int $limit)
915 $priority = self::nextPriority();
916 if (empty($priority)) {
917 Logger::info('No tasks found');
922 $stamp = (float)microtime(true);
923 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
924 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
925 self::$db_duration += (microtime(true) - $stamp);
926 while ($task = DBA::fetch($tasks)) {
927 $ids[] = $task['id'];
928 // Only continue that loop while we are storing commands that can be processed quickly
929 if (!empty($task['command'])) {
930 $command = $task['command'];
932 $command = json_decode($task['parameter'])[0];
935 if (!in_array($command, self::FAST_COMMANDS)) {
941 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
946 * Returns the priority of the next workerqueue job
948 * @return string priority
951 private static function nextPriority()
954 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
955 foreach ($priorities as $priority) {
956 $stamp = (float)microtime(true);
957 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
958 $waiting[$priority] = true;
960 self::$db_duration += (microtime(true) - $stamp);
963 if (!empty($waiting[PRIORITY_CRITICAL])) {
964 return PRIORITY_CRITICAL;
969 $stamp = (float)microtime(true);
970 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
971 self::$db_duration += (microtime(true) - $stamp);
972 while ($process = DBA::fetch($processes)) {
973 $running[$process['priority']] = $process['running'];
974 $running_total += $process['running'];
976 DBA::close($processes);
978 foreach ($priorities as $priority) {
979 if (!empty($waiting[$priority]) && empty($running[$priority])) {
980 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
985 $active = max(self::activeWorkers(), $running_total);
986 $priorities = max(count($waiting), count($running));
990 for ($i = 1; $i <= $priorities; ++$i) {
991 $total += pow($i, $exponent);
995 for ($i = 1; $i <= $priorities; ++$i) {
996 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
1000 foreach ($running as $priority => $workers) {
1001 if ($workers < $limit[$i++]) {
1002 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
1007 if (!empty($waiting)) {
1008 $priority = array_keys($waiting)[0];
1009 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
1017 * Find and claim the next worker process for us
1019 * @return boolean Have we found something?
1020 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1022 private static function findWorkerProcesses()
1024 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
1026 if (DI::config()->get('system', 'worker_multiple_fetch')) {
1028 foreach (self::getWorkerPIDList() as $pid => $count) {
1029 if ($count <= $fetch_limit) {
1036 $limit = $fetch_limit * count($pids);
1038 $pids = [getmypid()];
1039 $limit = $fetch_limit;
1042 $ids = self::nextProcess($limit);
1043 $limit -= count($ids);
1045 // If there is not enough results we check without priority limit
1047 $stamp = (float)microtime(true);
1048 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
1049 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1050 self::$db_duration += (microtime(true) - $stamp);
1052 while ($task = DBA::fetch($tasks)) {
1053 $ids[] = $task['id'];
1054 // Only continue that loop while we are storing commands that can be processed quickly
1055 if (!empty($task['command'])) {
1056 $command = $task['command'];
1058 $command = json_decode($task['parameter'])[0];
1060 if (!in_array($command, self::FAST_COMMANDS)) {
1071 // Assign the task ids to the workers
1073 foreach (array_unique($ids) as $id) {
1076 $pid = reset($pids);
1078 $worker[$pid][] = $id;
1081 $stamp = (float)microtime(true);
1082 foreach ($worker as $worker_pid => $worker_ids) {
1083 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1084 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1085 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1087 self::$db_duration += (microtime(true) - $stamp);
1088 self::$db_duration_write += (microtime(true) - $stamp);
1092 * Returns the next worker process
1094 * @return array worker processes
1095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1097 public static function workerProcess()
1099 // There can already be jobs for us in the queue.
1100 $waiting = self::getWaitingJobForPID();
1101 if (!empty($waiting)) {
1105 $stamp = (float)microtime(true);
1106 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1109 self::$lock_duration += (microtime(true) - $stamp);
1111 self::findWorkerProcesses();
1113 DI::lock()->release(self::LOCK_PROCESS);
1115 return self::getWaitingJobForPID();
1119 * Removes a workerqueue entry from the current process
1121 * @param Process $process the process behind the workerqueue
1124 * @throws \Exception
1126 public static function unclaimProcess(Process $process)
1128 $stamp = (float)microtime(true);
1129 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $process->pid, 'done' => false]);
1130 self::$db_duration += (microtime(true) - $stamp);
1131 self::$db_duration_write += (microtime(true) - $stamp);
1135 * Runs the cron processes
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 private static function runCron()
1142 Logger::info('Add cron entries');
1144 // Check for spooled items
1145 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1147 // Run the cron job that calls all other jobs
1148 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1150 // Cleaning dead processes
1151 self::killStaleWorkers();
1153 // Remove old entries from the workerqueue
1154 self::cleanWorkerQueue();
1158 * Remove old entries from the workerqueue
1162 private static function cleanWorkerQueue()
1164 DBA::delete('workerqueue', ["`done` AND `executed` < ?", DateTimeFormat::utc('now - 1 hour')]);
1166 // Optimizing this table only last seconds
1167 if (DI::config()->get('system', 'optimize_tables')) {
1168 // We are acquiring the two locks from the worker to avoid locking problems
1169 if (DI::lock()->acquire(Worker::LOCK_PROCESS, 10)) {
1170 if (DI::lock()->acquire(Worker::LOCK_WORKER, 10)) {
1171 DBA::e("OPTIMIZE TABLE `workerqueue`");
1172 DBA::e("OPTIMIZE TABLE `process`");
1173 DI::lock()->release(Worker::LOCK_WORKER);
1175 DI::lock()->release(Worker::LOCK_PROCESS);
1181 * Fork a child process
1183 * @param boolean $do_cron
1186 private static function forkProcess(bool $do_cron)
1188 if (DI::system()->isMinMemoryReached()) {
1189 Logger::warning('Memory limit reached - quitting');
1193 // Children inherit their parent's database connection.
1194 // To avoid problems we disconnect and connect both parent and child
1196 $pid = pcntl_fork();
1199 Logger::warning('Could not spawn worker');
1202 // The parent process continues here
1205 self::IPCSetJobState(true, $pid);
1206 Logger::info('Spawned new worker', ['pid' => $pid]);
1209 while (self::IPCJobsExists($pid) && (++$cycles < 100)) {
1213 Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1217 // We now are in the new worker
1221 $process = DI::process()->create(getmypid(), basename(__FILE__));
1224 while (!self::IPCJobsExists($process->pid) && (++$cycles < 100)) {
1228 Logger::info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]);
1230 self::processQueue($do_cron, $process);
1232 self::unclaimProcess($process);
1234 self::IPCSetJobState(false, $process->pid);
1235 DI::process()->delete($process);
1236 Logger::info('Worker ended', ['pid' => $process->pid]);
1241 * Spawns a new worker
1243 * @param bool $do_cron
1245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1247 public static function spawnWorker($do_cron = false)
1249 if (self::isDaemonMode() && DI::config()->get('system', 'worker_fork')) {
1250 self::forkProcess($do_cron);
1252 DI::system()->run('bin/worker.php', ['no_cron' => !$do_cron]);
1254 if (self::isDaemonMode()) {
1255 self::IPCSetJobState(false);
1260 * Adds tasks to the worker queue
1262 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1264 * next args are passed as $cmd command line
1265 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1266 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1268 * @return int "0" if worker queue entry already existed or there had been an error, otherwise the ID of the worker task
1269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1270 * @note $cmd and string args are surrounded with ""
1276 public static function add(...$args)
1278 if (!count($args)) {
1282 $arr = ['args' => $args, 'run_cmd' => true];
1284 Hook::callAll("proc_run", $arr);
1285 if (!$arr['run_cmd'] || !count($args)) {
1289 $priority = PRIORITY_MEDIUM;
1290 // Don't fork from frontend tasks by default
1291 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1292 $created = DateTimeFormat::utcNow();
1293 $delayed = DBA::NULL_DATETIME;
1294 $force_priority = false;
1296 $run_parameter = array_shift($args);
1298 if (is_int($run_parameter)) {
1299 $priority = $run_parameter;
1300 } elseif (is_array($run_parameter)) {
1301 if (isset($run_parameter['delayed'])) {
1302 $delayed = $run_parameter['delayed'];
1304 if (isset($run_parameter['priority'])) {
1305 $priority = $run_parameter['priority'];
1307 if (isset($run_parameter['created'])) {
1308 $created = $run_parameter['created'];
1310 if (isset($run_parameter['dont_fork'])) {
1311 $dont_fork = $run_parameter['dont_fork'];
1313 if (isset($run_parameter['force_priority'])) {
1314 $force_priority = $run_parameter['force_priority'];
1317 throw new \InvalidArgumentException('Priority number or task parameter array expected as first argument');
1320 $command = array_shift($args);
1321 $parameters = json_encode($args);
1322 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1325 if (!is_int($priority) || !in_array($priority, PRIORITIES)) {
1326 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1327 $priority = PRIORITY_MEDIUM;
1330 // Quit if there was a database error - a precaution for the update process to 3.5.3
1331 if (DBA::errorNo() != 0) {
1336 if (!DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1337 'priority' => $priority, 'next_try' => $delayed])) {
1340 $added = DBA::lastInsertId();
1341 } elseif ($force_priority) {
1342 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1345 // Set the IPC flag to ensure an immediate process execution via daemon
1346 if (self::isDaemonMode()) {
1347 self::IPCSetJobState(true);
1350 self::checkDaemonState();
1352 // Should we quit and wait for the worker to be called as a cronjob?
1357 // If there is a lock then we don't have to check for too much worker
1358 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1362 // If there are already enough workers running, don't fork another one
1363 $quit = self::tooMuchWorkers();
1364 DI::lock()->release(self::LOCK_WORKER);
1370 // Quit on daemon mode
1371 if (self::isDaemonMode()) {
1375 // Now call the worker to execute the jobs that we just added to the queue
1376 self::spawnWorker();
1381 public static function countWorkersByCommand(string $command)
1383 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1387 * Returns the next retrial level for worker jobs.
1388 * This function will skip levels when jobs are older.
1390 * @param array $queue Worker queue entry
1391 * @param integer $max_level maximum retrial level
1392 * @return integer the next retrial level value
1394 private static function getNextRetrial($queue, $max_level)
1396 $created = strtotime($queue['created']);
1397 $retrial_time = time() - $created;
1399 $new_retrial = $queue['retrial'] + 1;
1401 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1402 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1404 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1405 $new_retrial = $retrial;
1408 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1409 return $new_retrial;
1413 * Defers the current worker entry
1415 * @return boolean had the entry been deferred?
1416 * @throws \Exception
1418 public static function defer(): bool
1420 $queue = DI::app()->getQueue();
1422 if (empty($queue)) {
1426 $queue = self::checkPriority($queue);
1429 $priority = $queue['priority'];
1431 $max_level = DI::config()->get('system', 'worker_defer_limit');
1433 $new_retrial = self::getNextRetrial($queue, $max_level);
1435 if ($new_retrial > $max_level) {
1436 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]);
1440 // Calculate the delay until the next trial
1441 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1442 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1444 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1445 $priority = PRIORITY_MEDIUM;
1446 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1447 $priority = PRIORITY_LOW;
1448 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1449 $priority = PRIORITY_NEGLIGIBLE;
1452 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1454 $stamp = (float)microtime(true);
1455 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1456 DBA::update('workerqueue', $fields, ['id' => $id]);
1457 self::$db_duration += (microtime(true) - $stamp);
1458 self::$db_duration_write += (microtime(true) - $stamp);
1464 * Set the flag if some job is waiting
1466 * @param boolean $jobs Is there a waiting job?
1467 * @param int $key Key number
1468 * @throws \Exception
1470 public static function IPCSetJobState(bool $jobs, int $key = 0)
1472 $stamp = (float)microtime(true);
1473 DBA::replace('worker-ipc', ['jobs' => $jobs, 'key' => $key]);
1474 self::$db_duration += (microtime(true) - $stamp);
1475 self::$db_duration_write += (microtime(true) - $stamp);
1479 * Delete a key entry
1481 * @param int $key Key number
1482 * @throws \Exception
1484 public static function IPCDeleteJobState(int $key)
1486 $stamp = (float)microtime(true);
1487 DBA::delete('worker-ipc', ['key' => $key]);
1488 self::$db_duration += (microtime(true) - $stamp);
1489 self::$db_duration_write += (microtime(true) - $stamp);
1493 * Checks if some worker job waits to be executed
1495 * @param int $key Key number
1497 * @throws \Exception
1499 public static function IPCJobsExists(int $key = 0)
1501 $stamp = (float)microtime(true);
1502 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => $key]);
1503 self::$db_duration += (microtime(true) - $stamp);
1505 // When we don't have a row, no job is running
1506 if (!DBA::isResult($row)) {
1510 return (bool)$row['jobs'];
1514 * Checks if the worker is running in the daemon mode.
1518 public static function isDaemonMode()
1520 if (!is_null(self::$daemon_mode)) {
1521 return self::$daemon_mode;
1524 if (DI::mode()->getExecutor() == Mode::DAEMON) {
1528 $daemon_mode = DI::config()->get('system', 'worker_daemon_mode', false, true);
1530 return $daemon_mode;
1533 if (!function_exists('pcntl_fork')) {
1534 self::$daemon_mode = false;
1538 $pidfile = DI::config()->get('system', 'pidfile');
1539 if (empty($pidfile)) {
1540 // No pid file, no daemon
1541 self::$daemon_mode = false;
1545 if (!is_readable($pidfile)) {
1546 // No pid file. We assume that the daemon had been intentionally stopped.
1547 self::$daemon_mode = false;
1551 $pid = intval(file_get_contents($pidfile));
1552 $running = posix_kill($pid, 0);
1554 self::$daemon_mode = $running;
1559 * Test if the daemon is running. If not, it will be started
1563 private static function checkDaemonState()
1565 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1569 if (!DI::mode()->isNormal()) {
1573 // Check every minute if the daemon is running
1574 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1578 DI::config()->set('system', 'last_daemon_check', time());
1580 $pidfile = DI::config()->get('system', 'pidfile');
1581 if (empty($pidfile)) {
1582 // No pid file, no daemon
1586 if (!is_readable($pidfile)) {
1587 // No pid file. We assume that the daemon had been intentionally stopped.
1591 $pid = intval(file_get_contents($pidfile));
1592 if (posix_kill($pid, 0)) {
1593 Logger::info('Daemon process is running', ['pid' => $pid]);
1597 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1599 self::spawnDaemon();
1603 * Spawn a new daemon process
1607 private static function spawnDaemon()
1609 Logger::notice('Starting new daemon process');
1610 $command = 'bin/daemon.php';
1612 DI::system()->run($command, ['start']);
1613 Logger::notice('New daemon process started');
1617 * Check if the system is inside the defined maintenance window
1621 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1623 // Calculate the seconds of the start end end of the maintenance window
1624 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1625 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1627 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1629 if ($check_last_execution) {
1630 // Calculate the window duration
1631 $duration = max($start, $end) - min($start, $end);
1633 // Quit when the last cron execution had been after the previous window
1634 $last_cron = DI::config()->get('system', 'last_cron_daily');
1635 if ($last_cron + $duration > time()) {
1636 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)]);
1641 $current = time() % 86400;
1643 if ($start < $end) {
1644 // Execute if we are inside the window
1645 $execute = ($current >= $start) && ($current <= $end);
1647 // Don't execute if we are outside the window
1648 $execute = !(($current > $end) && ($current < $start));
1652 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)]);
1654 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)]);