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 if (self::IPCJobsExists(getmypid())) {
101 self::IPCSetJobState(false, getmypid());
103 // Don't refetch when a worker fetches tasks for multiple workers
104 $refetched = DI::config()->get('system', 'worker_multiple_fetch');
105 foreach ($r as $entry) {
106 // Assure that the priority is an integer value
107 $entry['priority'] = (int)$entry['priority'];
109 // The work will be done
110 if (!self::execute($entry)) {
111 Logger::notice('Process execution failed, quitting.');
115 // Trying to fetch new processes - but only once when successful
116 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
117 self::findWorkerProcesses();
118 DI::lock()->release(self::LOCK_PROCESS);
119 self::$state = self::STATE_REFETCH;
122 self::$state = self::STATE_SHORT_LOOP;
126 // To avoid the quitting of multiple workers only one worker at a time will execute the check
127 if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
128 self::$state = self::STATE_LONG_LOOP;
130 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
131 // Count active workers and compare them with a maximum value that depends on the load
132 if (self::tooMuchWorkers()) {
133 Logger::notice('Active worker limit reached, quitting.');
134 DI::lock()->release(self::LOCK_WORKER);
139 if (DI::process()->isMinMemoryReached()) {
140 Logger::warning('Memory limit reached, quitting.');
141 DI::lock()->release(self::LOCK_WORKER);
144 DI::lock()->release(self::LOCK_WORKER);
146 $last_check = time();
149 // Quit the worker once every cron interval
150 if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
151 Logger::info('Process lifetime reached, respawning.');
152 self::unclaimProcess();
153 if (self::isDaemonMode()) {
154 self::IPCSetJobState(true);
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 * Checks if the system is ready.
172 * Several system parameters like memory, connections and processes are checked.
176 public static function isReady()
178 // Count active workers and compare them with a maximum value that depends on the load
179 if (self::tooMuchWorkers()) {
180 Logger::notice('Active worker limit reached, quitting.');
184 // Do we have too few memory?
185 if (DI::process()->isMinMemoryReached()) {
186 Logger::warning('Memory limit reached, quitting.');
190 // Possibly there are too much database connections
191 if (self::maxConnectionsReached()) {
192 Logger::warning('Maximum connections reached, quitting.');
196 // Possibly there are too much database processes that block the system
197 if (DI::process()->isMaxProcessesReached()) {
198 Logger::warning('Maximum processes reached, quitting.');
206 * Check if non executed tasks do exist in the worker queue
208 * @return boolean Returns "true" if tasks are existing
211 public static function entriesExists()
213 $stamp = (float)microtime(true);
214 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
215 self::$db_duration += (microtime(true) - $stamp);
220 * Returns the number of deferred entries in the worker queue
222 * @return integer Number of deferred entries in the worker queue
225 private static function deferredEntries()
227 $stamp = (float)microtime(true);
228 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
229 self::$db_duration += (microtime(true) - $stamp);
230 self::$db_duration_count += (microtime(true) - $stamp);
235 * Returns the number of non executed entries in the worker queue
237 * @return integer Number of non executed entries in the worker queue
240 private static function totalEntries()
242 $stamp = (float)microtime(true);
243 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
244 self::$db_duration += (microtime(true) - $stamp);
245 self::$db_duration_count += (microtime(true) - $stamp);
250 * Returns the highest priority in the worker queue that isn't executed
252 * @return integer Number of active worker processes
255 private static function highestPriority()
257 $stamp = (float)microtime(true);
258 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
259 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
260 self::$db_duration += (microtime(true) - $stamp);
261 if (DBA::isResult($workerqueue)) {
262 return $workerqueue["priority"];
269 * Returns if a process with the given priority is running
271 * @param integer $priority The priority that should be checked
273 * @return integer Is there a process running with that priority?
276 private static function processWithPriorityActive($priority)
278 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
279 return DBA::exists('workerqueue', $condition);
283 * Execute a worker entry
285 * @param array $queue Workerqueue entry
287 * @return boolean "true" if further processing should be stopped
288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 public static function execute($queue)
294 // Quit when in maintenance
295 if (DI::config()->get('system', 'maintenance', false, true)) {
296 Logger::notice("Maintenance mode - quit process", ['pid' => $mypid]);
300 // Constantly check the number of parallel database processes
301 if (DI::process()->isMaxProcessesReached()) {
302 Logger::warning("Max processes reached for process", ['pid' => $mypid]);
306 // Constantly check the number of available database connections to let the frontend be accessible at any time
307 if (self::maxConnectionsReached()) {
308 Logger::warning("Max connection reached for process", ['pid' => $mypid]);
312 $argv = json_decode($queue['parameter'], true);
313 if (!empty($queue['command'])) {
314 array_unshift($argv, $queue['command']);
318 Logger::warning('Parameter is empty', ['queue' => $queue]);
322 // Check for existance and validity of the include file
325 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
326 // We constantly update the "executed" date every minute to avoid being killed too soon
327 if (!isset(self::$last_update)) {
328 self::$last_update = strtotime($queue["executed"]);
331 $age = (time() - self::$last_update) / 60;
332 self::$last_update = time();
335 $stamp = (float)microtime(true);
336 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
337 self::$db_duration += (microtime(true) - $stamp);
338 self::$db_duration_write += (microtime(true) - $stamp);
343 self::execFunction($queue, $include, $argv, true);
345 $stamp = (float)microtime(true);
346 $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
347 if (DBA::update('workerqueue', ['done' => true], $condition)) {
348 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
350 self::$db_duration = (microtime(true) - $stamp);
351 self::$db_duration_write += (microtime(true) - $stamp);
356 // The script could be provided as full path or only with the function name
357 if ($include == basename($include)) {
358 $include = "include/".$include.".php";
361 if (!validate_include($include)) {
362 Logger::warning("Include file is not valid", ['file' => $argv[0]]);
363 $stamp = (float)microtime(true);
364 DBA::delete('workerqueue', ['id' => $queue["id"]]);
365 self::$db_duration = (microtime(true) - $stamp);
366 self::$db_duration_write += (microtime(true) - $stamp);
370 require_once $include;
372 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
374 if (function_exists($funcname)) {
375 // We constantly update the "executed" date every minute to avoid being killed too soon
376 if (!isset(self::$last_update)) {
377 self::$last_update = strtotime($queue["executed"]);
380 $age = (time() - self::$last_update) / 60;
381 self::$last_update = time();
384 $stamp = (float)microtime(true);
385 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
386 self::$db_duration += (microtime(true) - $stamp);
387 self::$db_duration_write += (microtime(true) - $stamp);
390 self::execFunction($queue, $funcname, $argv, false);
392 $stamp = (float)microtime(true);
393 if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
394 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
396 self::$db_duration = (microtime(true) - $stamp);
397 self::$db_duration_write += (microtime(true) - $stamp);
399 Logger::warning("Function does not exist", ['function' => $funcname]);
400 $stamp = (float)microtime(true);
401 DBA::delete('workerqueue', ['id' => $queue["id"]]);
402 self::$db_duration = (microtime(true) - $stamp);
403 self::$db_duration_write += (microtime(true) - $stamp);
410 * Execute a function from the queue
412 * @param array $queue Workerqueue entry
413 * @param string $funcname name of the function
414 * @param array $argv Array of values to be passed to the function
415 * @param boolean $method_call boolean
417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 private static function execFunction($queue, $funcname, $argv, $method_call)
423 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
425 Logger::info('Pre execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
429 Logger::enableWorker($funcname);
431 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
433 $stamp = (float)microtime(true);
435 // We use the callstack here to analyze the performance of executed worker entries.
436 // For this reason the variables have to be initialized.
437 DI::profiler()->reset();
439 if (!in_array($queue['priority'], PRIORITIES)) {
440 Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
441 $queue['priority'] = PRIORITY_MEDIUM;
446 $up_duration = microtime(true) - self::$up_start;
448 // Reset global data to avoid interferences
451 // Set the workerLogger as new default logger
453 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
455 $funcname($argv, count($argv));
458 Logger::disableWorker();
462 $duration = (microtime(true) - $stamp);
464 /* With these values we can analyze how effective the worker is.
465 * The database and rest time should be low since this is the unproductive time.
466 * The execution time is the productive time.
467 * By changing parameters like the maximum number of workers we can check the effectivness.
469 $dbtotal = round(self::$db_duration, 2);
470 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
471 $dbcount = round(self::$db_duration_count, 2);
472 $dbstat = round(self::$db_duration_stat, 2);
473 $dbwrite = round(self::$db_duration_write, 2);
474 $dblock = round(self::$lock_duration, 2);
475 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
476 $exec = round($duration, 2);
478 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
480 self::$up_start = microtime(true);
481 self::$db_duration = 0;
482 self::$db_duration_count = 0;
483 self::$db_duration_stat = 0;
484 self::$db_duration_write = 0;
485 self::$lock_duration = 0;
487 if ($duration > 3600) {
488 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
489 } elseif ($duration > 600) {
490 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
491 } elseif ($duration > 300) {
492 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
493 } elseif ($duration > 120) {
494 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
497 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
499 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
502 Logger::info('Post execution cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
508 * Checks if the number of database connections has reached a critical limit.
510 * @return bool Are more than 3/4 of the maximum connections used?
511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
513 private static function maxConnectionsReached()
515 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
516 $max = DI::config()->get("system", "max_connections");
518 // Fetch the percentage level where the worker will get active
519 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
522 // the maximum number of possible user connections can be a system variable
523 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
524 if (DBA::isResult($r)) {
527 // Or it can be granted. This overrides the system variable
528 $stamp = (float)microtime(true);
529 $r = DBA::p('SHOW GRANTS');
530 self::$db_duration += (microtime(true) - $stamp);
531 while ($grants = DBA::fetch($r)) {
532 $grant = array_pop($grants);
533 if (stristr($grant, "GRANT USAGE ON")) {
534 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
542 // If $max is set we will use the processlist to determine the current number of connections
543 // The processlist only shows entries of the current user
545 $stamp = (float)microtime(true);
546 $r = DBA::p('SHOW PROCESSLIST');
547 self::$db_duration += (microtime(true) - $stamp);
548 $used = DBA::numRows($r);
551 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
553 $level = ($used / $max) * 100;
555 if ($level >= $maxlevel) {
556 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
561 // We will now check for the system values.
562 // This limit could be reached although the user limits are fine.
563 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
564 if (!DBA::isResult($r)) {
567 $max = intval($r["Value"]);
571 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
572 if (!DBA::isResult($r)) {
575 $used = intval($r["Value"]);
579 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
581 $level = $used / $max * 100;
583 if ($level < $maxlevel) {
586 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
591 * fix the queue entry if the worker process died
596 private static function killStaleWorkers()
598 $stamp = (float)microtime(true);
599 $entries = DBA::select(
601 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
602 ['NOT `done` AND `pid` != 0'],
603 ['order' => ['priority', 'retrial', 'created']]
605 self::$db_duration += (microtime(true) - $stamp);
607 while ($entry = DBA::fetch($entries)) {
608 if (!posix_kill($entry["pid"], 0)) {
609 $stamp = (float)microtime(true);
612 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
613 ['id' => $entry["id"]]
615 self::$db_duration += (microtime(true) - $stamp);
616 self::$db_duration_write += (microtime(true) - $stamp);
618 // Kill long running processes
619 // Check if the priority is in a valid range
620 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
621 $entry["priority"] = PRIORITY_MEDIUM;
624 // Define the maximum durations
625 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
626 $max_duration = $max_duration_defaults[$entry["priority"]];
628 $argv = json_decode($entry['parameter'], true);
629 if (!empty($entry['command'])) {
630 $command = $entry['command'];
631 } elseif (!empty($argv)) {
632 $command = array_shift($argv);
637 $command = basename($command);
639 // How long is the process already running?
640 $duration = (time() - strtotime($entry["executed"])) / 60;
641 if ($duration > $max_duration) {
642 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]);
643 posix_kill($entry["pid"], SIGTERM);
645 // We killed the stale process.
646 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
647 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
648 $new_priority = $entry["priority"];
649 if ($entry["priority"] == PRIORITY_HIGH) {
650 $new_priority = PRIORITY_MEDIUM;
651 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
652 $new_priority = PRIORITY_LOW;
653 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
654 $new_priority = PRIORITY_NEGLIGIBLE;
656 $stamp = (float)microtime(true);
659 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
660 ['id' => $entry["id"]]
662 self::$db_duration += (microtime(true) - $stamp);
663 self::$db_duration_write += (microtime(true) - $stamp);
665 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
669 DBA::close($entries);
673 * Checks if the number of active workers exceeds the given limits
675 * @return bool Are there too much workers running?
676 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 private static function tooMuchWorkers()
680 $queues = DI::config()->get("system", "worker_queues", 10);
682 $maxqueues = $queues;
684 $active = self::activeWorkers();
686 // Decrease the number of workers at higher load
687 $load = System::currentLoad();
689 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
691 /* Default exponent 3 causes queues to rapidly decrease as load increases.
692 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
693 * For some environments, this rapid decrease is not needed.
694 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
696 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
697 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
698 $queues = intval(ceil($slope * $maxqueues));
702 if (DI::config()->get('system', 'worker_jpm')) {
703 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
704 $jobs_per_minute = [];
705 foreach ($intervals as $interval) {
706 if ($interval == 0) {
709 $interval = (int)$interval;
712 $stamp = (float)microtime(true);
713 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
714 self::$db_duration += (microtime(true) - $stamp);
715 self::$db_duration_stat += (microtime(true) - $stamp);
716 if ($job = DBA::fetch($jobs)) {
717 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
721 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
724 // Create a list of queue entries grouped by their priority
725 $listitem = [0 => ''];
727 $idle_workers = $active;
729 $deferred = self::deferredEntries();
731 if (DI::config()->get('system', 'worker_debug')) {
732 $waiting_processes = 0;
733 // Now adding all processes with workerqueue entries
734 $stamp = (float)microtime(true);
735 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
736 self::$db_duration += (microtime(true) - $stamp);
737 self::$db_duration_stat += (microtime(true) - $stamp);
738 while ($entry = DBA::fetch($jobs)) {
739 $stamp = (float)microtime(true);
740 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
741 self::$db_duration += (microtime(true) - $stamp);
742 self::$db_duration_stat += (microtime(true) - $stamp);
743 if ($process = DBA::fetch($processes)) {
744 $idle_workers -= $process["running"];
745 $waiting_processes += $entry["entries"];
746 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
748 DBA::close($processes);
752 $waiting_processes = self::totalEntries();
753 $stamp = (float)microtime(true);
754 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
755 self::$db_duration += (microtime(true) - $stamp);
756 self::$db_duration_stat += (microtime(true) - $stamp);
758 while ($entry = DBA::fetch($jobs)) {
759 $idle_workers -= $entry["running"];
760 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
765 $waiting_processes -= $deferred;
767 $listitem[0] = "0:" . max(0, $idle_workers);
769 $processlist .= ' ('.implode(', ', $listitem).')';
771 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
772 $top_priority = self::highestPriority();
773 $high_running = self::processWithPriorityActive($top_priority);
775 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
776 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
777 $queues = $active + 1;
781 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
783 // Are there fewer workers running as possible? Then fork a new one.
784 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
785 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
786 if (self::isDaemonMode()) {
787 self::IPCSetJobState(true);
794 // if there are too much worker, we don't spawn a new one.
795 if (self::isDaemonMode() && ($active > $queues)) {
796 self::IPCSetJobState(false);
799 return $active > $queues;
803 * Returns the number of active worker processes
805 * @return integer Number of active worker processes
808 private static function activeWorkers()
810 $stamp = (float)microtime(true);
811 $count = DBA::count('process', ['command' => 'Worker.php']);
812 self::$db_duration += (microtime(true) - $stamp);
813 self::$db_duration_count += (microtime(true) - $stamp);
818 * Returns the number of active worker processes
820 * @return array List of worker process ids
823 private static function getWorkerPIDList()
826 $stamp = (float)microtime(true);
828 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
829 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
830 GROUP BY `process`.`pid`");
831 while ($queue = DBA::fetch($queues)) {
832 $ids[$queue['pid']] = $queue['entries'];
836 self::$db_duration += (microtime(true) - $stamp);
837 self::$db_duration_count += (microtime(true) - $stamp);
842 * Returns waiting jobs for the current process id
844 * @return array waiting workerqueue jobs
847 private static function getWaitingJobForPID()
849 $stamp = (float)microtime(true);
850 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
851 self::$db_duration += (microtime(true) - $stamp);
852 if (DBA::isResult($r)) {
853 return DBA::toArray($r);
861 * Returns the next jobs that should be executed
863 * @return array array with next jobs
866 private static function nextProcess(int $limit)
868 $priority = self::nextPriority();
869 if (empty($priority)) {
870 Logger::info('No tasks found');
875 $stamp = (float)microtime(true);
876 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
877 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
878 self::$db_duration += (microtime(true) - $stamp);
879 while ($task = DBA::fetch($tasks)) {
880 $ids[] = $task['id'];
881 // Only continue that loop while we are storing commands that can be processed quickly
882 if (!empty($task['command'])) {
883 $command = $task['command'];
885 $command = json_decode($task['parameter'])[0];
888 if (!in_array($command, self::FAST_COMMANDS)) {
894 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
899 * Returns the priority of the next workerqueue job
901 * @return string priority
904 private static function nextPriority()
907 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
908 foreach ($priorities as $priority) {
909 $stamp = (float)microtime(true);
910 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
911 $waiting[$priority] = true;
913 self::$db_duration += (microtime(true) - $stamp);
916 if (!empty($waiting[PRIORITY_CRITICAL])) {
917 return PRIORITY_CRITICAL;
922 $stamp = (float)microtime(true);
923 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
924 self::$db_duration += (microtime(true) - $stamp);
925 while ($process = DBA::fetch($processes)) {
926 $running[$process['priority']] = $process['running'];
927 $running_total += $process['running'];
929 DBA::close($processes);
931 foreach ($priorities as $priority) {
932 if (!empty($waiting[$priority]) && empty($running[$priority])) {
933 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
938 $active = max(self::activeWorkers(), $running_total);
939 $priorities = max(count($waiting), count($running));
943 for ($i = 1; $i <= $priorities; ++$i) {
944 $total += pow($i, $exponent);
948 for ($i = 1; $i <= $priorities; ++$i) {
949 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
953 foreach ($running as $priority => $workers) {
954 if ($workers < $limit[$i++]) {
955 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
960 if (!empty($waiting)) {
961 $priority = array_keys($waiting)[0];
962 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
970 * Find and claim the next worker process for us
972 * @return boolean Have we found something?
973 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
975 private static function findWorkerProcesses()
977 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
979 if (DI::config()->get('system', 'worker_multiple_fetch')) {
981 foreach (self::getWorkerPIDList() as $pid => $count) {
982 if ($count <= $fetch_limit) {
989 $limit = $fetch_limit * count($pids);
991 $pids = [getmypid()];
992 $limit = $fetch_limit;
995 $ids = self::nextProcess($limit);
996 $limit -= count($ids);
998 // If there is not enough results we check without priority limit
1000 $stamp = (float)microtime(true);
1001 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
1002 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
1003 self::$db_duration += (microtime(true) - $stamp);
1005 while ($task = DBA::fetch($tasks)) {
1006 $ids[] = $task['id'];
1007 // Only continue that loop while we are storing commands that can be processed quickly
1008 if (!empty($task['command'])) {
1009 $command = $task['command'];
1011 $command = json_decode($task['parameter'])[0];
1013 if (!in_array($command, self::FAST_COMMANDS)) {
1024 // Assign the task ids to the workers
1026 foreach (array_unique($ids) as $id) {
1029 $pid = reset($pids);
1031 $worker[$pid][] = $id;
1034 $stamp = (float)microtime(true);
1035 foreach ($worker as $worker_pid => $worker_ids) {
1036 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1037 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1038 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1040 self::$db_duration += (microtime(true) - $stamp);
1041 self::$db_duration_write += (microtime(true) - $stamp);
1045 * Returns the next worker process
1047 * @return array worker processes
1048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1050 public static function workerProcess()
1052 // There can already be jobs for us in the queue.
1053 $waiting = self::getWaitingJobForPID();
1054 if (!empty($waiting)) {
1058 $stamp = (float)microtime(true);
1059 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1062 self::$lock_duration += (microtime(true) - $stamp);
1064 self::findWorkerProcesses();
1066 DI::lock()->release(self::LOCK_PROCESS);
1068 return self::getWaitingJobForPID();
1072 * Removes a workerqueue entry from the current process
1075 * @throws \Exception
1077 public static function unclaimProcess()
1079 $mypid = getmypid();
1081 $stamp = (float)microtime(true);
1082 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1083 self::$db_duration += (microtime(true) - $stamp);
1084 self::$db_duration_write += (microtime(true) - $stamp);
1088 * Call the front end worker
1091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1093 public static function callWorker()
1095 if (!DI::config()->get("system", "frontend_worker")) {
1099 $url = DI::baseUrl() . '/worker';
1100 DI::httpRequest()->fetch($url, 1);
1104 * Call the front end worker if there aren't any active
1107 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109 public static function executeIfIdle()
1111 self::checkDaemonState();
1113 if (!DI::config()->get("system", "frontend_worker")) {
1117 // Do we have "proc_open"? Then we can fork the worker
1118 if (function_exists("proc_open")) {
1119 // When was the last time that we called the worker?
1120 // Less than one minute? Then we quit
1121 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1125 DI::config()->set("system", "worker_started", time());
1127 // Do we have enough running workers? Then we quit here.
1128 if (self::tooMuchWorkers()) {
1129 // Cleaning dead processes
1130 self::killStaleWorkers();
1131 DI::modelProcess()->deleteInactive();
1138 Logger::info('Call worker');
1139 self::spawnWorker();
1143 // We cannot execute background processes.
1144 // We now run the processes from the frontend.
1145 // This won't work with long running processes.
1148 self::clearProcesses();
1150 $workers = self::activeWorkers();
1152 if ($workers == 0) {
1158 * Removes long running worker processes
1161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1163 public static function clearProcesses()
1165 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1167 /// @todo We should clean up the corresponding workerqueue entries as well
1168 $stamp = (float)microtime(true);
1169 $condition = ["`created` < ? AND `command` = 'worker.php'",
1170 DateTimeFormat::utc("now - ".$timeout." minutes")];
1171 DBA::delete('process', $condition);
1172 self::$db_duration = (microtime(true) - $stamp);
1173 self::$db_duration_write += (microtime(true) - $stamp);
1177 * Runs the cron processes
1180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1182 private static function runCron()
1184 Logger::info('Add cron entries');
1186 // Check for spooled items
1187 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1189 // Run the cron job that calls all other jobs
1190 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1192 // Cleaning dead processes
1193 self::killStaleWorkers();
1197 * Fork a child process
1199 * @param boolean $do_cron
1202 private static function forkProcess(bool $do_cron)
1204 if (DI::process()->isMinMemoryReached()) {
1205 Logger::warning('Memory limit reached - quitting');
1209 // Children inherit their parent's database connection.
1210 // To avoid problems we disconnect and connect both parent and child
1212 $pid = pcntl_fork();
1215 Logger::warning('Could not spawn worker');
1218 // The parent process continues here
1220 Logger::info('Spawned new worker', ['pid' => $pid]);
1221 self::IPCSetJobState(true, $pid);
1224 while (self::IPCJobsExists($pid) && (++$cycles < 100)) {
1228 Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1232 // We now are in the new worker
1234 Logger::info('Worker spawned', ['pid' => getmypid()]);
1237 while (!self::IPCJobsExists($pid) && (++$cycles < 100)) {
1241 Logger::info('Parent is ready', ['pid' => getmypid(), 'wait_cycles' => $cycles]);
1243 self::processQueue($do_cron);
1245 self::unclaimProcess();
1247 self::IPCSetJobState(false, getmypid());
1248 DI::process()->end();
1249 Logger::info('Worker ended', ['pid' => getmypid()]);
1254 * Spawns a new worker
1256 * @param bool $do_cron
1258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1260 public static function spawnWorker($do_cron = false)
1262 if (self::isDaemonMode() && DI::config()->get('system', 'worker_fork')) {
1263 self::forkProcess($do_cron);
1265 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1266 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1267 $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1269 if (self::isDaemonMode()) {
1270 self::IPCSetJobState(false);
1275 * Adds tasks to the worker queue
1277 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1279 * next args are passed as $cmd command line
1280 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1281 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1283 * @return boolean "false" if worker queue entry already existed or there had been an error
1284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1285 * @note $cmd and string args are surrounded with ""
1291 public static function add($cmd)
1293 $args = func_get_args();
1295 if (!count($args)) {
1299 $arr = ['args' => $args, 'run_cmd' => true];
1301 Hook::callAll("proc_run", $arr);
1302 if (!$arr['run_cmd'] || !count($args)) {
1306 $priority = PRIORITY_MEDIUM;
1307 // Don't fork from frontend tasks by default
1308 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1309 $created = DateTimeFormat::utcNow();
1310 $delayed = DBA::NULL_DATETIME;
1311 $force_priority = false;
1313 $run_parameter = array_shift($args);
1315 if (is_int($run_parameter)) {
1316 $priority = $run_parameter;
1317 } elseif (is_array($run_parameter)) {
1318 if (isset($run_parameter['delayed'])) {
1319 $delayed = $run_parameter['delayed'];
1321 if (isset($run_parameter['priority'])) {
1322 $priority = $run_parameter['priority'];
1324 if (isset($run_parameter['created'])) {
1325 $created = $run_parameter['created'];
1327 if (isset($run_parameter['dont_fork'])) {
1328 $dont_fork = $run_parameter['dont_fork'];
1330 if (isset($run_parameter['force_priority'])) {
1331 $force_priority = $run_parameter['force_priority'];
1335 $command = array_shift($args);
1336 $parameters = json_encode($args);
1337 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1340 if (!in_array($priority, PRIORITIES)) {
1341 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1342 $priority = PRIORITY_MEDIUM;
1345 // Quit if there was a database error - a precaution for the update process to 3.5.3
1346 if (DBA::errorNo() != 0) {
1351 $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1352 'priority' => $priority, 'next_try' => $delayed]);
1356 } elseif ($force_priority) {
1357 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1360 // Set the IPC flag to ensure an immediate process execution via daemon
1361 if (self::isDaemonMode()) {
1362 self::IPCSetJobState(true);
1365 self::checkDaemonState();
1367 // Should we quit and wait for the worker to be called as a cronjob?
1372 // If there is a lock then we don't have to check for too much worker
1373 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1377 // If there are already enough workers running, don't fork another one
1378 $quit = self::tooMuchWorkers();
1379 DI::lock()->release(self::LOCK_WORKER);
1385 // Quit on daemon mode
1386 if (self::isDaemonMode()) {
1390 // Now call the worker to execute the jobs that we just added to the queue
1391 self::spawnWorker();
1396 public static function countWorkersByCommand(string $command)
1398 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1402 * Returns the next retrial level for worker jobs.
1403 * This function will skip levels when jobs are older.
1405 * @param array $queue Worker queue entry
1406 * @param integer $max_level maximum retrial level
1407 * @return integer the next retrial level value
1409 private static function getNextRetrial($queue, $max_level)
1411 $created = strtotime($queue['created']);
1412 $retrial_time = time() - $created;
1414 $new_retrial = $queue['retrial'] + 1;
1416 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1417 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1419 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1420 $new_retrial = $retrial;
1423 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1424 return $new_retrial;
1428 * Defers the current worker entry
1430 * @return boolean had the entry been deferred?
1432 public static function defer()
1434 if (empty(DI::app()->queue)) {
1438 $queue = DI::app()->queue;
1440 $retrial = $queue['retrial'];
1442 $priority = $queue['priority'];
1444 $max_level = DI::config()->get('system', 'worker_defer_limit');
1446 $new_retrial = self::getNextRetrial($queue, $max_level);
1448 if ($new_retrial > $max_level) {
1449 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]);
1453 // Calculate the delay until the next trial
1454 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1455 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1457 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1458 $priority = PRIORITY_MEDIUM;
1459 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1460 $priority = PRIORITY_LOW;
1461 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1462 $priority = PRIORITY_NEGLIGIBLE;
1465 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1467 $stamp = (float)microtime(true);
1468 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1469 DBA::update('workerqueue', $fields, ['id' => $id]);
1470 self::$db_duration += (microtime(true) - $stamp);
1471 self::$db_duration_write += (microtime(true) - $stamp);
1477 * Set the flag if some job is waiting
1479 * @param boolean $jobs Is there a waiting job?
1480 * @throws \Exception
1482 public static function IPCSetJobState(bool $jobs, int $key = 0)
1484 $stamp = (float)microtime(true);
1485 DBA::replace('worker-ipc', ['jobs' => $jobs, 'key' => $key]);
1486 self::$db_duration += (microtime(true) - $stamp);
1487 self::$db_duration_write += (microtime(true) - $stamp);
1491 * Checks if some worker job waits to be executed
1494 * @throws \Exception
1496 public static function IPCJobsExists(int $key = 0)
1498 $stamp = (float)microtime(true);
1499 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => $key]);
1500 self::$db_duration += (microtime(true) - $stamp);
1502 // When we don't have a row, no job is running
1503 if (!DBA::isResult($row)) {
1507 return (bool)$row['jobs'];
1511 * Checks if the worker is running in the daemon mode.
1515 public static function isDaemonMode()
1517 if (!is_null(self::$daemon_mode)) {
1518 return self::$daemon_mode;
1521 if (DI::mode()->getExecutor() == Mode::DAEMON) {
1525 $daemon_mode = DI::config()->get('system', 'worker_daemon_mode', false, true);
1527 return $daemon_mode;
1530 if (!function_exists('pcntl_fork')) {
1531 self::$daemon_mode = false;
1535 $pidfile = DI::config()->get('system', 'pidfile');
1536 if (empty($pidfile)) {
1537 // No pid file, no daemon
1538 self::$daemon_mode = false;
1542 if (!is_readable($pidfile)) {
1543 // No pid file. We assume that the daemon had been intentionally stopped.
1544 self::$daemon_mode = false;
1548 $pid = intval(file_get_contents($pidfile));
1549 $running = posix_kill($pid, 0);
1551 self::$daemon_mode = $running;
1556 * Test if the daemon is running. If not, it will be started
1560 private static function checkDaemonState()
1562 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1566 if (!DI::mode()->isNormal()) {
1570 // Check every minute if the daemon is running
1571 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1575 DI::config()->set('system', 'last_daemon_check', time());
1577 $pidfile = DI::config()->get('system', 'pidfile');
1578 if (empty($pidfile)) {
1579 // No pid file, no daemon
1583 if (!is_readable($pidfile)) {
1584 // No pid file. We assume that the daemon had been intentionally stopped.
1588 $pid = intval(file_get_contents($pidfile));
1589 if (posix_kill($pid, 0)) {
1590 Logger::info('Daemon process is running', ['pid' => $pid]);
1594 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1596 self::spawnDaemon();
1600 * Spawn a new daemon process
1604 private static function spawnDaemon()
1606 Logger::notice('Starting new daemon process');
1607 $command = 'bin/daemon.php';
1609 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1610 $process->run($command, ['start']);
1611 Logger::notice('New daemon process started');
1615 * Check if the system is inside the defined maintenance window
1619 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1621 // Calculate the seconds of the start end end of the maintenance window
1622 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1623 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1625 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1627 if ($check_last_execution) {
1628 // Calculate the window duration
1629 $duration = max($start, $end) - min($start, $end);
1631 // Quit when the last cron execution had been after the previous window
1632 $last_cron = DI::config()->get('system', 'last_cron_daily');
1633 if ($last_cron + $duration > time()) {
1634 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)]);
1639 $current = time() % 86400;
1641 if ($start < $end) {
1642 // Execute if we are inside the window
1643 $execute = ($current >= $start) && ($current <= $end);
1645 // Don't execute if we are outside the window
1646 $execute = !(($current > $end) && ($current < $start));
1650 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)]);
1652 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)]);