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;
98 // We fetch the next queue entry that is about to be executed
99 while ($r = self::workerProcess()) {
100 // Don't refetch when a worker fetches tasks for multiple workers
101 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
102 foreach ($r as $entry) {
103 // Assure that the priority is an integer value
104 $entry['priority'] = (int)$entry['priority'];
106 // The work will be done
107 if (!self::execute($entry)) {
108 Logger::notice('Process execution failed, quitting.');
112 // Trying to fetch new processes - but only once when successful
113 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
114 self::findWorkerProcesses();
115 DI::lock()->release(self::LOCK_PROCESS);
116 self::$state = self::STATE_REFETCH;
119 self::$state = self::STATE_SHORT_LOOP;
123 // To avoid the quitting of multiple workers only one worker at a time will execute the check
124 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
125 self::$state = self::STATE_LONG_LOOP;
127 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
128 // Count active workers and compare them with a maximum value that depends on the load
129 if (self::tooMuchWorkers()) {
130 Logger::notice('Active worker limit reached, quitting.');
131 DI::lock()->release(self::LOCK_WORKER);
136 if (DI::process()->isMinMemoryReached()) {
137 Logger::warning('Memory limit reached, quitting.');
138 DI::lock()->release(self::LOCK_WORKER);
141 DI::lock()->release(self::LOCK_WORKER);
143 $last_check = time();
146 // Quit the worker once every cron interval
147 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
148 Logger::info('Process lifetime reached, respawning.');
149 self::unclaimProcess();
150 if (self::isDaemonMode()) {
151 self::IPCSetJobState(true);
159 // Cleaning up. Possibly not needed, but it doesn't harm anything.
160 if (self::isDaemonMode()) {
161 self::IPCSetJobState(false);
163 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
167 * Checks if the system is ready.
169 * Several system parameters like memory, connections and processes are checked.
173 public static function isReady()
175 // Count active workers and compare them with a maximum value that depends on the load
176 if (self::tooMuchWorkers()) {
177 Logger::notice('Active worker limit reached, quitting.');
181 // Do we have too few memory?
182 if (DI::process()->isMinMemoryReached()) {
183 Logger::warning('Memory limit reached, quitting.');
187 // Possibly there are too much database connections
188 if (self::maxConnectionsReached()) {
189 Logger::warning('Maximum connections reached, quitting.');
193 // Possibly there are too much database processes that block the system
194 if (DI::process()->isMaxProcessesReached()) {
195 Logger::warning('Maximum processes reached, quitting.');
203 * Check if non executed tasks do exist in the worker queue
205 * @return boolean Returns "true" if tasks are existing
208 public static function entriesExists()
210 $stamp = (float)microtime(true);
211 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
212 self::$db_duration += (microtime(true) - $stamp);
217 * Returns the number of deferred entries in the worker queue
219 * @return integer Number of deferred entries in the worker queue
222 private static function deferredEntries()
224 $stamp = (float)microtime(true);
225 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
226 self::$db_duration += (microtime(true) - $stamp);
227 self::$db_duration_count += (microtime(true) - $stamp);
232 * Returns the number of non executed entries in the worker queue
234 * @return integer Number of non executed entries in the worker queue
237 private static function totalEntries()
239 $stamp = (float)microtime(true);
240 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
241 self::$db_duration += (microtime(true) - $stamp);
242 self::$db_duration_count += (microtime(true) - $stamp);
247 * Returns the highest priority in the worker queue that isn't executed
249 * @return integer Number of active worker processes
252 private static function highestPriority()
254 $stamp = (float)microtime(true);
255 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
256 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
257 self::$db_duration += (microtime(true) - $stamp);
258 if (DBA::isResult($workerqueue)) {
259 return $workerqueue["priority"];
266 * Returns if a process with the given priority is running
268 * @param integer $priority The priority that should be checked
270 * @return integer Is there a process running with that priority?
273 private static function processWithPriorityActive($priority)
275 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
276 return DBA::exists('workerqueue', $condition);
280 * Execute a worker entry
282 * @param array $queue Workerqueue entry
284 * @return boolean "true" if further processing should be stopped
285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
287 public static function execute($queue)
291 // Quit when in maintenance
292 if (DI::config()->get('system', 'maintenance', false, true)) {
293 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
297 // Constantly check the number of parallel database processes
298 if (DI::process()->isMaxProcessesReached()) {
299 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
303 // Constantly check the number of available database connections to let the frontend be accessible at any time
304 if (self::maxConnectionsReached()) {
305 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
309 $argv = json_decode($queue['parameter'], true);
310 if (!empty($queue['command'])) {
311 array_unshift($argv, $queue['command']);
315 Logger::warning('Parameter is empty', ['queue' => $queue]);
319 // Check for existance and validity of the include file
322 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
323 // We constantly update the "executed" date every minute to avoid being killed too soon
324 if (!isset(self::$last_update)) {
325 self::$last_update = strtotime($queue["executed"]);
328 $age = (time() - self::$last_update) / 60;
329 self::$last_update = time();
332 $stamp = (float)microtime(true);
333 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
334 self::$db_duration += (microtime(true) - $stamp);
335 self::$db_duration_write += (microtime(true) - $stamp);
340 self::execFunction($queue, $include, $argv, true);
342 $stamp = (float)microtime(true);
343 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
344 if (DBA::update('workerqueue', ['done' => true], $condition)) {
345 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
347 self::$db_duration = (microtime(true) - $stamp);
348 self::$db_duration_write += (microtime(true) - $stamp);
353 // The script could be provided as full path or only with the function name
354 if ($include == basename($include)) {
355 $include = "include/".$include.".php";
358 if (!validate_include($include)) {
359 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
360 $stamp = (float)microtime(true);
361 DBA::delete('workerqueue', ['id' => $queue["id"]]);
362 self::$db_duration = (microtime(true) - $stamp);
363 self::$db_duration_write += (microtime(true) - $stamp);
367 require_once $include;
369 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
371 if (function_exists($funcname)) {
372 // We constantly update the "executed" date every minute to avoid being killed too soon
373 if (!isset(self::$last_update)) {
374 self::$last_update = strtotime($queue["executed"]);
377 $age = (time() - self::$last_update) / 60;
378 self::$last_update = time();
381 $stamp = (float)microtime(true);
382 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
383 self::$db_duration += (microtime(true) - $stamp);
384 self::$db_duration_write += (microtime(true) - $stamp);
387 self::execFunction($queue, $funcname, $argv, false);
389 $stamp = (float)microtime(true);
390 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
391 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
393 self::$db_duration = (microtime(true) - $stamp);
394 self::$db_duration_write += (microtime(true) - $stamp);
396 Logger::warning("Function does not exist", ['function' => $funcname]);
397 $stamp = (float)microtime(true);
398 DBA::delete('workerqueue', ['id' => $queue["id"]]);
399 self::$db_duration = (microtime(true) - $stamp);
400 self::$db_duration_write += (microtime(true) - $stamp);
407 * Execute a function from the queue
409 * @param array $queue Workerqueue entry
410 * @param string $funcname name of the function
411 * @param array $argv Array of values to be passed to the function
412 * @param boolean $method_call boolean
414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
416 private static function execFunction($queue, $funcname, $argv, $method_call)
420 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
422 Logger::info('Pre execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
426 Logger::enableWorker($funcname);
428 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
430 $stamp = (float)microtime(true);
432 // We use the callstack here to analyze the performance of executed worker entries.
433 // For this reason the variables have to be initialized.
434 DI::profiler()->reset();
436 if (!in_array($queue['priority'], PRIORITIES)) {
437 Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
438 $queue['priority'] = PRIORITY_MEDIUM;
443 $up_duration = microtime(true) - self::$up_start;
445 // Reset global data to avoid interferences
448 // Set the workerLogger as new default logger
450 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
452 $funcname($argv, count($argv));
455 Logger::disableWorker();
459 $duration = (microtime(true) - $stamp);
461 /* With these values we can analyze how effective the worker is.
462 * The database and rest time should be low since this is the unproductive time.
463 * The execution time is the productive time.
464 * By changing parameters like the maximum number of workers we can check the effectivness.
466 $dbtotal = round(self::$db_duration, 2);
467 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
468 $dbcount = round(self::$db_duration_count, 2);
469 $dbstat = round(self::$db_duration_stat, 2);
470 $dbwrite = round(self::$db_duration_write, 2);
471 $dblock = round(self::$lock_duration, 2);
472 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
473 $exec = round($duration, 2);
475 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
477 self::$up_start = microtime(true);
478 self::$db_duration = 0;
479 self::$db_duration_count = 0;
480 self::$db_duration_stat = 0;
481 self::$db_duration_write = 0;
482 self::$lock_duration = 0;
484 if ($duration > 3600) {
485 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
486 } elseif ($duration > 600) {
487 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
488 } elseif ($duration > 300) {
489 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
490 } elseif ($duration > 120) {
491 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
494 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
496 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
499 Logger::info('Post execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
505 * Checks if the number of database connections has reached a critical limit.
507 * @return bool Are more than 3/4 of the maximum connections used?
508 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
510 private static function maxConnectionsReached()
512 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
513 $max = DI::config()->get("system", "max_connections");
515 // Fetch the percentage level where the worker will get active
516 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
519 // the maximum number of possible user connections can be a system variable
520 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
521 if (DBA::isResult($r)) {
524 // Or it can be granted. This overrides the system variable
525 $stamp = (float)microtime(true);
526 $r = DBA::p('SHOW GRANTS');
527 self::$db_duration += (microtime(true) - $stamp);
528 while ($grants = DBA::fetch($r)) {
529 $grant = array_pop($grants);
530 if (stristr($grant, "GRANT USAGE ON")) {
531 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
539 // If $max is set we will use the processlist to determine the current number of connections
540 // The processlist only shows entries of the current user
542 $stamp = (float)microtime(true);
543 $r = DBA::p('SHOW PROCESSLIST');
544 self::$db_duration += (microtime(true) - $stamp);
545 $used = DBA::numRows($r);
548 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
550 $level = ($used / $max) * 100;
552 if ($level >= $maxlevel) {
553 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
558 // We will now check for the system values.
559 // This limit could be reached although the user limits are fine.
560 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
561 if (!DBA::isResult($r)) {
564 $max = intval($r["Value"]);
568 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
569 if (!DBA::isResult($r)) {
572 $used = intval($r["Value"]);
576 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
578 $level = $used / $max * 100;
580 if ($level < $maxlevel) {
583 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
588 * fix the queue entry if the worker process died
593 private static function killStaleWorkers()
595 $stamp = (float)microtime(true);
596 $entries = DBA::select(
598 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
599 ['NOT `done` AND `pid` != 0'],
600 ['order' => ['priority', 'retrial', 'created']]
602 self::$db_duration += (microtime(true) - $stamp);
604 while ($entry = DBA::fetch($entries)) {
605 if (!posix_kill($entry["pid"], 0)) {
606 $stamp = (float)microtime(true);
609 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
610 ['id' => $entry["id"]]
612 self::$db_duration += (microtime(true) - $stamp);
613 self::$db_duration_write += (microtime(true) - $stamp);
615 // Kill long running processes
616 // Check if the priority is in a valid range
617 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
618 $entry["priority"] = PRIORITY_MEDIUM;
621 // Define the maximum durations
622 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
623 $max_duration = $max_duration_defaults[$entry["priority"]];
625 $argv = json_decode($entry['parameter'], true);
626 if (!empty($entry['command'])) {
627 $command = $entry['command'];
628 } elseif (!empty($argv)) {
629 $command = array_shift($argv);
634 $command = basename($command);
636 // How long is the process already running?
637 $duration = (time() - strtotime($entry["executed"])) / 60;
638 if ($duration > $max_duration) {
639 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]);
640 posix_kill($entry["pid"], SIGTERM);
642 // We killed the stale process.
643 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
644 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
645 $new_priority = $entry["priority"];
646 if ($entry["priority"] == PRIORITY_HIGH) {
647 $new_priority = PRIORITY_MEDIUM;
648 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
649 $new_priority = PRIORITY_LOW;
650 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
651 $new_priority = PRIORITY_NEGLIGIBLE;
653 $stamp = (float)microtime(true);
656 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
657 ['id' => $entry["id"]]
659 self::$db_duration += (microtime(true) - $stamp);
660 self::$db_duration_write += (microtime(true) - $stamp);
662 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
666 DBA::close($entries);
670 * Checks if the number of active workers exceeds the given limits
672 * @return bool Are there too much workers running?
673 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675 private static function tooMuchWorkers()
677 $queues = DI::config()->get("system", "worker_queues", 10);
679 $maxqueues = $queues;
681 $active = self::activeWorkers();
683 // Decrease the number of workers at higher load
684 $load = System::currentLoad();
686 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
688 /* Default exponent 3 causes queues to rapidly decrease as load increases.
689 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
690 * For some environments, this rapid decrease is not needed.
691 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
693 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
694 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
695 $queues = intval(ceil($slope * $maxqueues));
699 if (DI::config()->get('system', 'worker_jpm')) {
700 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
701 $jobs_per_minute = [];
702 foreach ($intervals as $interval) {
703 if ($interval == 0) {
706 $interval = (int)$interval;
709 $stamp = (float)microtime(true);
710 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
711 self::$db_duration += (microtime(true) - $stamp);
712 self::$db_duration_stat += (microtime(true) - $stamp);
713 if ($job = DBA::fetch($jobs)) {
714 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
718 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
721 // Create a list of queue entries grouped by their priority
722 $listitem = [0 => ''];
724 $idle_workers = $active;
726 $deferred = self::deferredEntries();
728 if (DI::config()->get('system', 'worker_debug')) {
729 $waiting_processes = 0;
730 // Now adding all processes with workerqueue entries
731 $stamp = (float)microtime(true);
732 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
733 self::$db_duration += (microtime(true) - $stamp);
734 self::$db_duration_stat += (microtime(true) - $stamp);
735 while ($entry = DBA::fetch($jobs)) {
736 $stamp = (float)microtime(true);
737 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
738 self::$db_duration += (microtime(true) - $stamp);
739 self::$db_duration_stat += (microtime(true) - $stamp);
740 if ($process = DBA::fetch($processes)) {
741 $idle_workers -= $process["running"];
742 $waiting_processes += $entry["entries"];
743 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
745 DBA::close($processes);
749 $waiting_processes = self::totalEntries();
750 $stamp = (float)microtime(true);
751 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
752 self::$db_duration += (microtime(true) - $stamp);
753 self::$db_duration_stat += (microtime(true) - $stamp);
755 while ($entry = DBA::fetch($jobs)) {
756 $idle_workers -= $entry["running"];
757 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
762 $waiting_processes -= $deferred;
764 $listitem[0] = "0:" . max(0, $idle_workers);
766 $processlist .= ' ('.implode(', ', $listitem).')';
768 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
769 $top_priority = self::highestPriority();
770 $high_running = self::processWithPriorityActive($top_priority);
772 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
773 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
774 $queues = $active + 1;
778 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
780 // Are there fewer workers running as possible? Then fork a new one.
781 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
782 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
783 if (self::isDaemonMode()) {
784 self::IPCSetJobState(true);
791 // if there are too much worker, we don't spawn a new one.
792 if (self::isDaemonMode() && ($active > $queues)) {
793 self::IPCSetJobState(false);
796 return $active > $queues;
800 * Returns the number of active worker processes
802 * @return integer Number of active worker processes
805 private static function activeWorkers()
807 $stamp = (float)microtime(true);
808 $count = DBA::count('process', ['command' => 'Worker.php']);
809 self::$db_duration += (microtime(true) - $stamp);
810 self::$db_duration_count += (microtime(true) - $stamp);
815 * Returns the number of active worker processes
817 * @return array List of worker process ids
820 private static function getWorkerPIDList()
823 $stamp = (float)microtime(true);
825 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
826 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
827 GROUP BY `process`.`pid`");
828 while ($queue = DBA::fetch($queues)) {
829 $ids[$queue['pid']] = $queue['entries'];
833 self::$db_duration += (microtime(true) - $stamp);
834 self::$db_duration_count += (microtime(true) - $stamp);
839 * Returns waiting jobs for the current process id
841 * @return array waiting workerqueue jobs
844 private static function getWaitingJobForPID()
846 $stamp = (float)microtime(true);
847 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
848 self::$db_duration += (microtime(true) - $stamp);
849 if (DBA::isResult($r)) {
850 return DBA::toArray($r);
858 * Returns the next jobs that should be executed
860 * @return array array with next jobs
863 private static function nextProcess(int $limit)
865 $priority = self::nextPriority();
866 if (empty($priority)) {
867 Logger::info('No tasks found');
872 $stamp = (float)microtime(true);
873 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
874 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
875 self::$db_duration += (microtime(true) - $stamp);
876 while ($task = DBA::fetch($tasks)) {
877 $ids[] = $task['id'];
878 // Only continue that loop while we are storing commands that can be processed quickly
879 if (!empty($task['command'])) {
880 $command = $task['command'];
882 $command = json_decode($task['parameter'])[0];
885 if (!in_array($command, self::FAST_COMMANDS)) {
891 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
896 * Returns the priority of the next workerqueue job
898 * @return string priority
901 private static function nextPriority()
904 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
905 foreach ($priorities as $priority) {
906 $stamp = (float)microtime(true);
907 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
908 $waiting[$priority] = true;
910 self::$db_duration += (microtime(true) - $stamp);
913 if (!empty($waiting[PRIORITY_CRITICAL])) {
914 return PRIORITY_CRITICAL;
919 $stamp = (float)microtime(true);
920 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
921 self::$db_duration += (microtime(true) - $stamp);
922 while ($process = DBA::fetch($processes)) {
923 $running[$process['priority']] = $process['running'];
924 $running_total += $process['running'];
926 DBA::close($processes);
928 foreach ($priorities as $priority) {
929 if (!empty($waiting[$priority]) && empty($running[$priority])) {
930 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
935 $active = max(self::activeWorkers(), $running_total);
936 $priorities = max(count($waiting), count($running));
940 for ($i = 1; $i <= $priorities; ++$i) {
941 $total += pow($i, $exponent);
945 for ($i = 1; $i <= $priorities; ++$i) {
946 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
950 foreach ($running as $priority => $workers) {
951 if ($workers < $limit[$i++]) {
952 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
957 if (!empty($waiting)) {
958 $priority = array_keys($waiting)[0];
959 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
967 * Find and claim the next worker process for us
969 * @return boolean Have we found something?
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
972 private static function findWorkerProcesses()
974 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
976 if (DI::config()->get('system', 'worker_multiple_fetch')) {
978 foreach (self::getWorkerPIDList() as $pid => $count) {
979 if ($count <= $fetch_limit) {
986 $limit = $fetch_limit * count($pids);
988 $pids = [getmypid()];
989 $limit = $fetch_limit;
992 $ids = self::nextProcess($limit);
993 $limit -= count($ids);
995 // If there is not enough results we check without priority limit
997 $stamp = (float)microtime(true);
998 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
999 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1000 self::$db_duration += (microtime(true) - $stamp);
1002 while ($task = DBA::fetch($tasks)) {
1003 $ids[] = $task['id'];
1004 // Only continue that loop while we are storing commands that can be processed quickly
1005 if (!empty($task['command'])) {
1006 $command = $task['command'];
1008 $command = json_decode($task['parameter'])[0];
1010 if (!in_array($command, self::FAST_COMMANDS)) {
1021 // Assign the task ids to the workers
1023 foreach (array_unique($ids) as $id) {
1026 $pid = reset($pids);
1028 $worker[$pid][] = $id;
1031 $stamp = (float)microtime(true);
1032 foreach ($worker as $worker_pid => $worker_ids) {
1033 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1034 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1035 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1037 self::$db_duration += (microtime(true) - $stamp);
1038 self::$db_duration_write += (microtime(true) - $stamp);
1042 * Returns the next worker process
1044 * @return array worker processes
1045 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1047 public static function workerProcess()
1049 // There can already be jobs for us in the queue.
1050 $waiting = self::getWaitingJobForPID();
1051 if (!empty($waiting)) {
1055 $stamp = (float)microtime(true);
1056 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1059 self::$lock_duration += (microtime(true) - $stamp);
1061 self::findWorkerProcesses();
1063 DI::lock()->release(self::LOCK_PROCESS);
1065 return self::getWaitingJobForPID();
1069 * Removes a workerqueue entry from the current process
1072 * @throws \Exception
1074 public static function unclaimProcess()
1076 $mypid = getmypid();
1078 $stamp = (float)microtime(true);
1079 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1080 self::$db_duration += (microtime(true) - $stamp);
1081 self::$db_duration_write += (microtime(true) - $stamp);
1085 * Call the front end worker
1088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1090 public static function callWorker()
1092 if (!DI::config()->get("system", "frontend_worker")) {
1096 $url = DI::baseUrl() . '/worker';
1097 DI::httpRequest()->fetch($url, 1);
1101 * Call the front end worker if there aren't any active
1104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1106 public static function executeIfIdle()
1108 self::checkDaemonState();
1110 if (!DI::config()->get("system", "frontend_worker")) {
1114 // Do we have "proc_open"? Then we can fork the worker
1115 if (function_exists("proc_open")) {
1116 // When was the last time that we called the worker?
1117 // Less than one minute? Then we quit
1118 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1122 DI::config()->set("system", "worker_started", time());
1124 // Do we have enough running workers? Then we quit here.
1125 if (self::tooMuchWorkers()) {
1126 // Cleaning dead processes
1127 self::killStaleWorkers();
1128 DI::modelProcess()->deleteInactive();
1135 Logger::info('Call worker');
1136 self::spawnWorker();
1140 // We cannot execute background processes.
1141 // We now run the processes from the frontend.
1142 // This won't work with long running processes.
1145 self::clearProcesses();
1147 $workers = self::activeWorkers();
1149 if ($workers == 0) {
1155 * Removes long running worker processes
1158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1160 public static function clearProcesses()
1162 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1164 /// @todo We should clean up the corresponding workerqueue entries as well
1165 $stamp = (float)microtime(true);
1166 $condition = ["`created` < ? AND `command` = 'worker.php'",
1167 DateTimeFormat::utc("now - ".$timeout." minutes")];
1168 DBA::delete('process', $condition);
1169 self::$db_duration = (microtime(true) - $stamp);
1170 self::$db_duration_write += (microtime(true) - $stamp);
1174 * Runs the cron processes
1177 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1179 private static function runCron()
1181 Logger::info('Add cron entries');
1183 // Check for spooled items
1184 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1186 // Run the cron job that calls all other jobs
1187 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1189 // Cleaning dead processes
1190 self::killStaleWorkers();
1194 * Fork a child process
1196 * @param boolean $do_cron
1199 private static function forkProcess(bool $do_cron)
1201 if (DI::process()->isMinMemoryReached()) {
1202 Logger::warning('Memory limit reached - quitting');
1206 // Children inherit their parent's database connection.
1207 // To avoid problems we disconnect and connect both parent and child
1209 $pid = pcntl_fork();
1212 Logger::warning('Could not spawn worker');
1215 // The parent process continues here
1217 Logger::info('Spawned new worker', ['cron' => $do_cron, 'pid' => $pid]);
1221 // We now are in the new worker
1223 Logger::info('Worker spawned', ['cron' => $do_cron, 'pid' => getmypid()]);
1225 DI::process()->start();
1227 self::processQueue($do_cron);
1229 self::unclaimProcess();
1231 DI::process()->end();
1232 Logger::info('Worker ended', ['cron' => $do_cron, 'pid' => getmypid()]);
1237 * Spawns a new worker
1239 * @param bool $do_cron
1241 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1243 public static function spawnWorker($do_cron = false)
1245 Logger::notice("Spawn", ['do_cron' => $do_cron, 'callstack' => System::callstack(20)]);
1246 // Worker and daemon are started from the command line.
1247 // This means that this is executed by a PHP interpreter without runtime limitations
1248 if (function_exists('pcntl_fork') && in_array(DI::mode()->getExecutor(), [Mode::DAEMON, Mode::WORKER])) {
1249 self::forkProcess($do_cron);
1251 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1252 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1253 $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1256 // after spawning we have to remove the flag.
1257 if (self::isDaemonMode()) {
1258 self::IPCSetJobState(false);
1263 * Adds tasks to the worker queue
1265 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1267 * next args are passed as $cmd command line
1268 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1269 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1271 * @return boolean "false" if worker queue entry already existed or there had been an error
1272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1273 * @note $cmd and string args are surrounded with ""
1279 public static function add($cmd)
1281 $args = func_get_args();
1283 if (!count($args)) {
1287 $arr = ['args' => $args, 'run_cmd' => true];
1289 Hook::callAll("proc_run", $arr);
1290 if (!$arr['run_cmd'] || !count($args)) {
1294 $priority = PRIORITY_MEDIUM;
1295 // Don't fork from frontend tasks by default
1296 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1297 $created = DateTimeFormat::utcNow();
1298 $delayed = DBA::NULL_DATETIME;
1299 $force_priority = false;
1301 $run_parameter = array_shift($args);
1303 if (is_int($run_parameter)) {
1304 $priority = $run_parameter;
1305 } elseif (is_array($run_parameter)) {
1306 if (isset($run_parameter['delayed'])) {
1307 $delayed = $run_parameter['delayed'];
1309 if (isset($run_parameter['priority'])) {
1310 $priority = $run_parameter['priority'];
1312 if (isset($run_parameter['created'])) {
1313 $created = $run_parameter['created'];
1315 if (isset($run_parameter['dont_fork'])) {
1316 $dont_fork = $run_parameter['dont_fork'];
1318 if (isset($run_parameter['force_priority'])) {
1319 $force_priority = $run_parameter['force_priority'];
1323 $command = array_shift($args);
1324 $parameters = json_encode($args);
1325 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1328 if (!in_array($priority, PRIORITIES)) {
1329 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1330 $priority = PRIORITY_MEDIUM;
1333 // Quit if there was a database error - a precaution for the update process to 3.5.3
1334 if (DBA::errorNo() != 0) {
1339 $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1340 'priority' => $priority, 'next_try' => $delayed]);
1344 } elseif ($force_priority) {
1345 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1348 // Set the IPC flag to ensure an immediate process execution via daemon
1349 if (self::isDaemonMode()) {
1350 self::IPCSetJobState(true);
1353 self::checkDaemonState();
1355 // Should we quit and wait for the worker to be called as a cronjob?
1360 // If there is a lock then we don't have to check for too much worker
1361 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1365 // If there are already enough workers running, don't fork another one
1366 $quit = self::tooMuchWorkers();
1367 DI::lock()->release(self::LOCK_WORKER);
1373 // Quit on daemon mode
1374 if (self::isDaemonMode()) {
1378 // Now call the worker to execute the jobs that we just added to the queue
1379 self::spawnWorker();
1384 public static function countWorkersByCommand(string $command)
1386 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1390 * Returns the next retrial level for worker jobs.
1391 * This function will skip levels when jobs are older.
1393 * @param array $queue Worker queue entry
1394 * @param integer $max_level maximum retrial level
1395 * @return integer the next retrial level value
1397 private static function getNextRetrial($queue, $max_level)
1399 $created = strtotime($queue['created']);
1400 $retrial_time = time() - $created;
1402 $new_retrial = $queue['retrial'] + 1;
1404 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1405 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1407 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1408 $new_retrial = $retrial;
1411 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1412 return $new_retrial;
1416 * Defers the current worker entry
1418 * @return boolean had the entry been deferred?
1420 public static function defer()
1422 if (empty(DI::app()->queue)) {
1426 $queue = DI::app()->queue;
1428 $retrial = $queue['retrial'];
1430 $priority = $queue['priority'];
1432 $max_level = DI::config()->get('system', 'worker_defer_limit');
1434 $new_retrial = self::getNextRetrial($queue, $max_level);
1436 if ($new_retrial > $max_level) {
1437 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]);
1441 // Calculate the delay until the next trial
1442 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1443 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1445 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1446 $priority = PRIORITY_MEDIUM;
1447 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1448 $priority = PRIORITY_LOW;
1449 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1450 $priority = PRIORITY_NEGLIGIBLE;
1453 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1455 $stamp = (float)microtime(true);
1456 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1457 DBA::update('workerqueue', $fields, ['id' => $id]);
1458 self::$db_duration += (microtime(true) - $stamp);
1459 self::$db_duration_write += (microtime(true) - $stamp);
1465 * Set the flag if some job is waiting
1467 * @param boolean $jobs Is there a waiting job?
1468 * @throws \Exception
1470 public static function IPCSetJobState($jobs)
1472 $stamp = (float)microtime(true);
1473 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1474 self::$db_duration += (microtime(true) - $stamp);
1475 self::$db_duration_write += (microtime(true) - $stamp);
1479 * Checks if some worker job waits to be executed
1482 * @throws \Exception
1484 public static function IPCJobsExists()
1486 $stamp = (float)microtime(true);
1487 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1488 self::$db_duration += (microtime(true) - $stamp);
1490 // When we don't have a row, no job is running
1491 if (!DBA::isResult($row)) {
1495 return (bool)$row['jobs'];
1499 * Checks if the worker is running in the daemon mode.
1503 public static function isDaemonMode()
1505 if (!is_null(self::$daemon_mode)) {
1506 return self::$daemon_mode;
1509 if (DI::mode()->getExecutor() == Mode::DAEMON) {
1513 $daemon_mode = DI::config()->get('system', 'worker_daemon_mode', false, true);
1515 return $daemon_mode;
1518 $pidfile = DI::config()->get('system', 'pidfile');
1519 if (empty($pidfile)) {
1520 // No pid file, no daemon
1521 self::$daemon_mode = false;
1525 if (!is_readable($pidfile)) {
1526 // No pid file. We assume that the daemon had been intentionally stopped.
1527 self::$daemon_mode = false;
1531 $pid = intval(file_get_contents($pidfile));
1532 $running = posix_kill($pid, 0);
1534 self::$daemon_mode = $running;
1539 * Test if the daemon is running. If not, it will be started
1543 private static function checkDaemonState()
1545 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1549 if (!DI::mode()->isNormal()) {
1553 // Check every minute if the daemon is running
1554 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1558 DI::config()->set('system', 'last_daemon_check', time());
1560 $pidfile = DI::config()->get('system', 'pidfile');
1561 if (empty($pidfile)) {
1562 // No pid file, no daemon
1566 if (!is_readable($pidfile)) {
1567 // No pid file. We assume that the daemon had been intentionally stopped.
1571 $pid = intval(file_get_contents($pidfile));
1572 if (posix_kill($pid, 0)) {
1573 Logger::info('Daemon process is running', ['pid' => $pid]);
1577 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1579 self::spawnDaemon();
1583 * Spawn a new daemon process
1587 private static function spawnDaemon()
1589 Logger::notice('Starting new daemon process');
1590 $command = 'bin/daemon.php';
1592 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1593 $process->run($command, ['start']);
1594 Logger::notice('New daemon process started');
1598 * Check if the system is inside the defined maintenance window
1602 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1604 // Calculate the seconds of the start end end of the maintenance window
1605 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1606 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1608 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1610 if ($check_last_execution) {
1611 // Calculate the window duration
1612 $duration = max($start, $end) - min($start, $end);
1614 // Quit when the last cron execution had been after the previous window
1615 $last_cron = DI::config()->get('system', 'last_cron_daily');
1616 if ($last_cron + $duration > time()) {
1617 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)]);
1622 $current = time() % 86400;
1624 if ($start < $end) {
1625 // Execute if we are inside the window
1626 $execute = ($current >= $start) && ($current <= $end);
1628 // Don't execute if we are outside the window
1629 $execute = !(($current > $end) && ($current < $start));
1633 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)]);
1635 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)]);