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 Logger::enableWorker($funcname);
422 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
424 $stamp = (float)microtime(true);
426 // We use the callstack here to analyze the performance of executed worker entries.
427 // For this reason the variables have to be initialized.
428 DI::profiler()->reset();
430 if (!in_array($queue['priority'], PRIORITIES)) {
431 Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
432 $queue['priority'] = PRIORITY_MEDIUM;
437 $up_duration = microtime(true) - self::$up_start;
439 // Reset global data to avoid interferences
442 // Set the workerLogger as new default logger
444 call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
446 $funcname($argv, count($argv));
449 Logger::disableWorker();
453 $duration = (microtime(true) - $stamp);
455 /* With these values we can analyze how effective the worker is.
456 * The database and rest time should be low since this is the unproductive time.
457 * The execution time is the productive time.
458 * By changing parameters like the maximum number of workers we can check the effectivness.
460 $dbtotal = round(self::$db_duration, 2);
461 $dbread = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
462 $dbcount = round(self::$db_duration_count, 2);
463 $dbstat = round(self::$db_duration_stat, 2);
464 $dbwrite = round(self::$db_duration_write, 2);
465 $dblock = round(self::$lock_duration, 2);
466 $rest = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
467 $exec = round($duration, 2);
469 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
471 self::$up_start = microtime(true);
472 self::$db_duration = 0;
473 self::$db_duration_count = 0;
474 self::$db_duration_stat = 0;
475 self::$db_duration_write = 0;
476 self::$lock_duration = 0;
478 if ($duration > 3600) {
479 Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
480 } elseif ($duration > 600) {
481 Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
482 } elseif ($duration > 300) {
483 Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
484 } elseif ($duration > 120) {
485 Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
488 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
490 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
492 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
495 Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
501 * Checks if the number of database connections has reached a critical limit.
503 * @return bool Are more than 3/4 of the maximum connections used?
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 private static function maxConnectionsReached()
508 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
509 $max = DI::config()->get("system", "max_connections");
511 // Fetch the percentage level where the worker will get active
512 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
515 // the maximum number of possible user connections can be a system variable
516 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
517 if (DBA::isResult($r)) {
520 // Or it can be granted. This overrides the system variable
521 $stamp = (float)microtime(true);
522 $r = DBA::p('SHOW GRANTS');
523 self::$db_duration += (microtime(true) - $stamp);
524 while ($grants = DBA::fetch($r)) {
525 $grant = array_pop($grants);
526 if (stristr($grant, "GRANT USAGE ON")) {
527 if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
535 // If $max is set we will use the processlist to determine the current number of connections
536 // The processlist only shows entries of the current user
538 $stamp = (float)microtime(true);
539 $r = DBA::p('SHOW PROCESSLIST');
540 self::$db_duration += (microtime(true) - $stamp);
541 $used = DBA::numRows($r);
544 Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
546 $level = ($used / $max) * 100;
548 if ($level >= $maxlevel) {
549 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
554 // We will now check for the system values.
555 // This limit could be reached although the user limits are fine.
556 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
557 if (!DBA::isResult($r)) {
560 $max = intval($r["Value"]);
564 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
565 if (!DBA::isResult($r)) {
568 $used = intval($r["Value"]);
572 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
574 $level = $used / $max * 100;
576 if ($level < $maxlevel) {
579 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
584 * fix the queue entry if the worker process died
589 private static function killStaleWorkers()
591 $stamp = (float)microtime(true);
592 $entries = DBA::select(
594 ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
595 ['NOT `done` AND `pid` != 0'],
596 ['order' => ['priority', 'retrial', 'created']]
598 self::$db_duration += (microtime(true) - $stamp);
600 while ($entry = DBA::fetch($entries)) {
601 if (!posix_kill($entry["pid"], 0)) {
602 $stamp = (float)microtime(true);
605 ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
606 ['id' => $entry["id"]]
608 self::$db_duration += (microtime(true) - $stamp);
609 self::$db_duration_write += (microtime(true) - $stamp);
611 // Kill long running processes
612 // Check if the priority is in a valid range
613 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
614 $entry["priority"] = PRIORITY_MEDIUM;
617 // Define the maximum durations
618 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
619 $max_duration = $max_duration_defaults[$entry["priority"]];
621 $argv = json_decode($entry['parameter'], true);
622 if (!empty($entry['command'])) {
623 $command = $entry['command'];
624 } elseif (!empty($argv)) {
625 $command = array_shift($argv);
630 $command = basename($command);
632 // How long is the process already running?
633 $duration = (time() - strtotime($entry["executed"])) / 60;
634 if ($duration > $max_duration) {
635 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]);
636 posix_kill($entry["pid"], SIGTERM);
638 // We killed the stale process.
639 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
640 // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
641 $new_priority = $entry["priority"];
642 if ($entry["priority"] == PRIORITY_HIGH) {
643 $new_priority = PRIORITY_MEDIUM;
644 } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
645 $new_priority = PRIORITY_LOW;
646 } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
647 $new_priority = PRIORITY_NEGLIGIBLE;
649 $stamp = (float)microtime(true);
652 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
653 ['id' => $entry["id"]]
655 self::$db_duration += (microtime(true) - $stamp);
656 self::$db_duration_write += (microtime(true) - $stamp);
658 Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
662 DBA::close($entries);
666 * Checks if the number of active workers exceeds the given limits
668 * @return bool Are there too much workers running?
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
671 private static function tooMuchWorkers()
673 $queues = DI::config()->get("system", "worker_queues", 10);
675 $maxqueues = $queues;
677 $active = self::activeWorkers();
679 // Decrease the number of workers at higher load
680 $load = System::currentLoad();
682 $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
684 /* Default exponent 3 causes queues to rapidly decrease as load increases.
685 * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
686 * For some environments, this rapid decrease is not needed.
687 * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
689 $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
690 $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
691 $queues = intval(ceil($slope * $maxqueues));
695 if (DI::config()->get('system', 'worker_jpm')) {
696 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
697 $jobs_per_minute = [];
698 foreach ($intervals as $interval) {
699 if ($interval == 0) {
702 $interval = (int)$interval;
705 $stamp = (float)microtime(true);
706 $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
707 self::$db_duration += (microtime(true) - $stamp);
708 self::$db_duration_stat += (microtime(true) - $stamp);
709 if ($job = DBA::fetch($jobs)) {
710 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
714 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
717 // Create a list of queue entries grouped by their priority
718 $listitem = [0 => ''];
720 $idle_workers = $active;
722 $deferred = self::deferredEntries();
724 if (DI::config()->get('system', 'worker_debug')) {
725 $waiting_processes = 0;
726 // Now adding all processes with workerqueue entries
727 $stamp = (float)microtime(true);
728 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
729 self::$db_duration += (microtime(true) - $stamp);
730 self::$db_duration_stat += (microtime(true) - $stamp);
731 while ($entry = DBA::fetch($jobs)) {
732 $stamp = (float)microtime(true);
733 $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
734 self::$db_duration += (microtime(true) - $stamp);
735 self::$db_duration_stat += (microtime(true) - $stamp);
736 if ($process = DBA::fetch($processes)) {
737 $idle_workers -= $process["running"];
738 $waiting_processes += $entry["entries"];
739 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
741 DBA::close($processes);
745 $waiting_processes = self::totalEntries();
746 $stamp = (float)microtime(true);
747 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
748 self::$db_duration += (microtime(true) - $stamp);
749 self::$db_duration_stat += (microtime(true) - $stamp);
751 while ($entry = DBA::fetch($jobs)) {
752 $idle_workers -= $entry["running"];
753 $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
758 $waiting_processes -= $deferred;
760 $listitem[0] = "0:" . max(0, $idle_workers);
762 $processlist .= ' ('.implode(', ', $listitem).')';
764 if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
765 $top_priority = self::highestPriority();
766 $high_running = self::processWithPriorityActive($top_priority);
768 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
769 Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
770 $queues = $active + 1;
774 Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
776 // Are there fewer workers running as possible? Then fork a new one.
777 if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
778 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
779 if (self::isDaemonMode()) {
780 self::IPCSetJobState(true);
787 // if there are too much worker, we don't spawn a new one.
788 if (self::isDaemonMode() && ($active > $queues)) {
789 self::IPCSetJobState(false);
792 return $active > $queues;
796 * Returns the number of active worker processes
798 * @return integer Number of active worker processes
801 private static function activeWorkers()
803 $stamp = (float)microtime(true);
804 $count = DBA::count('process', ['command' => 'Worker.php']);
805 self::$db_duration += (microtime(true) - $stamp);
806 self::$db_duration_count += (microtime(true) - $stamp);
811 * Returns the number of active worker processes
813 * @return array List of worker process ids
816 private static function getWorkerPIDList()
819 $stamp = (float)microtime(true);
821 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
822 LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
823 GROUP BY `process`.`pid`");
824 while ($queue = DBA::fetch($queues)) {
825 $ids[$queue['pid']] = $queue['entries'];
829 self::$db_duration += (microtime(true) - $stamp);
830 self::$db_duration_count += (microtime(true) - $stamp);
835 * Returns waiting jobs for the current process id
837 * @return array waiting workerqueue jobs
840 private static function getWaitingJobForPID()
842 $stamp = (float)microtime(true);
843 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
844 self::$db_duration += (microtime(true) - $stamp);
845 if (DBA::isResult($r)) {
846 return DBA::toArray($r);
854 * Returns the next jobs that should be executed
856 * @return array array with next jobs
859 private static function nextProcess(int $limit)
861 $priority = self::nextPriority();
862 if (empty($priority)) {
863 Logger::info('No tasks found');
868 $stamp = (float)microtime(true);
869 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
870 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
871 self::$db_duration += (microtime(true) - $stamp);
872 while ($task = DBA::fetch($tasks)) {
873 $ids[] = $task['id'];
874 // Only continue that loop while we are storing commands that can be processed quickly
875 if (!empty($task['command'])) {
876 $command = $task['command'];
878 $command = json_decode($task['parameter'])[0];
881 if (!in_array($command, self::FAST_COMMANDS)) {
887 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
892 * Returns the priority of the next workerqueue job
894 * @return string priority
897 private static function nextPriority()
900 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
901 foreach ($priorities as $priority) {
902 $stamp = (float)microtime(true);
903 if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
904 $waiting[$priority] = true;
906 self::$db_duration += (microtime(true) - $stamp);
909 if (!empty($waiting[PRIORITY_CRITICAL])) {
910 return PRIORITY_CRITICAL;
915 $stamp = (float)microtime(true);
916 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
917 self::$db_duration += (microtime(true) - $stamp);
918 while ($process = DBA::fetch($processes)) {
919 $running[$process['priority']] = $process['running'];
920 $running_total += $process['running'];
922 DBA::close($processes);
924 foreach ($priorities as $priority) {
925 if (!empty($waiting[$priority]) && empty($running[$priority])) {
926 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
931 $active = max(self::activeWorkers(), $running_total);
932 $priorities = max(count($waiting), count($running));
936 for ($i = 1; $i <= $priorities; ++$i) {
937 $total += pow($i, $exponent);
941 for ($i = 1; $i <= $priorities; ++$i) {
942 $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
946 foreach ($running as $priority => $workers) {
947 if ($workers < $limit[$i++]) {
948 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
953 if (!empty($waiting)) {
954 $priority = array_keys($waiting)[0];
955 Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
963 * Find and claim the next worker process for us
965 * @return boolean Have we found something?
966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 private static function findWorkerProcesses()
970 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
972 if (DI::config()->get('system', 'worker_multiple_fetch')) {
974 foreach (self::getWorkerPIDList() as $pid => $count) {
975 if ($count <= $fetch_limit) {
982 $limit = $fetch_limit * count($pids);
984 $pids = [getmypid()];
985 $limit = $fetch_limit;
988 $ids = self::nextProcess($limit);
989 $limit -= count($ids);
991 // If there is not enough results we check without priority limit
993 $stamp = (float)microtime(true);
994 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
995 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
996 self::$db_duration += (microtime(true) - $stamp);
998 while ($task = DBA::fetch($tasks)) {
999 $ids[] = $task['id'];
1000 // Only continue that loop while we are storing commands that can be processed quickly
1001 if (!empty($task['command'])) {
1002 $command = $task['command'];
1004 $command = json_decode($task['parameter'])[0];
1006 if (!in_array($command, self::FAST_COMMANDS)) {
1017 // Assign the task ids to the workers
1019 foreach (array_unique($ids) as $id) {
1022 $pid = reset($pids);
1024 $worker[$pid][] = $id;
1027 $stamp = (float)microtime(true);
1028 foreach ($worker as $worker_pid => $worker_ids) {
1029 Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1030 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1031 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1033 self::$db_duration += (microtime(true) - $stamp);
1034 self::$db_duration_write += (microtime(true) - $stamp);
1038 * Returns the next worker process
1040 * @return array worker processes
1041 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 public static function workerProcess()
1045 // There can already be jobs for us in the queue.
1046 $waiting = self::getWaitingJobForPID();
1047 if (!empty($waiting)) {
1051 $stamp = (float)microtime(true);
1052 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1055 self::$lock_duration += (microtime(true) - $stamp);
1057 self::findWorkerProcesses();
1059 DI::lock()->release(self::LOCK_PROCESS);
1061 return self::getWaitingJobForPID();
1065 * Removes a workerqueue entry from the current process
1068 * @throws \Exception
1070 public static function unclaimProcess()
1072 $mypid = getmypid();
1074 $stamp = (float)microtime(true);
1075 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1076 self::$db_duration += (microtime(true) - $stamp);
1077 self::$db_duration_write += (microtime(true) - $stamp);
1081 * Call the front end worker
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1086 public static function callWorker()
1088 if (!DI::config()->get("system", "frontend_worker")) {
1092 $url = DI::baseUrl() . '/worker';
1093 DI::httpRequest()->fetch($url, 1);
1097 * Call the front end worker if there aren't any active
1100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102 public static function executeIfIdle()
1104 self::checkDaemonState();
1106 if (!DI::config()->get("system", "frontend_worker")) {
1110 // Do we have "proc_open"? Then we can fork the worker
1111 if (function_exists("proc_open")) {
1112 // When was the last time that we called the worker?
1113 // Less than one minute? Then we quit
1114 if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1118 DI::config()->set("system", "worker_started", time());
1120 // Do we have enough running workers? Then we quit here.
1121 if (self::tooMuchWorkers()) {
1122 // Cleaning dead processes
1123 self::killStaleWorkers();
1124 DI::modelProcess()->deleteInactive();
1131 Logger::info('Call worker');
1132 self::spawnWorker();
1136 // We cannot execute background processes.
1137 // We now run the processes from the frontend.
1138 // This won't work with long running processes.
1141 self::clearProcesses();
1143 $workers = self::activeWorkers();
1145 if ($workers == 0) {
1151 * Removes long running worker processes
1154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1156 public static function clearProcesses()
1158 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1160 /// @todo We should clean up the corresponding workerqueue entries as well
1161 $stamp = (float)microtime(true);
1162 $condition = ["`created` < ? AND `command` = 'worker.php'",
1163 DateTimeFormat::utc("now - ".$timeout." minutes")];
1164 DBA::delete('process', $condition);
1165 self::$db_duration = (microtime(true) - $stamp);
1166 self::$db_duration_write += (microtime(true) - $stamp);
1170 * Runs the cron processes
1173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1175 private static function runCron()
1177 Logger::info('Add cron entries');
1179 // Check for spooled items
1180 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1182 // Run the cron job that calls all other jobs
1183 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1185 // Cleaning dead processes
1186 self::killStaleWorkers();
1190 * Fork a child process
1192 * @param boolean $do_cron
1195 private static function forkProcess(bool $do_cron)
1197 if (DI::process()->isMinMemoryReached()) {
1198 Logger::warning('Memory limit reached - quitting');
1202 // Children inherit their parent's database connection.
1203 // To avoid problems we disconnect and connect both parent and child
1205 $pid = pcntl_fork();
1208 Logger::warning('Could not spawn worker');
1211 // The parent process continues here
1213 Logger::info('Spawned new worker', ['cron' => $do_cron, 'pid' => $pid]);
1217 // We now are in the new worker
1219 Logger::info('Worker spawned', ['cron' => $do_cron, 'pid' => getmypid()]);
1221 DI::process()->start();
1223 self::processQueue($do_cron);
1225 self::unclaimProcess();
1227 DI::process()->end();
1228 Logger::info('Worker ended', ['cron' => $do_cron, 'pid' => getmypid()]);
1233 * Spawns a new worker
1235 * @param bool $do_cron
1237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1239 public static function spawnWorker($do_cron = false)
1241 Logger::notice("Spawn", ['do_cron' => $do_cron, 'callstack' => System::callstack(20)]);
1242 // Worker and daemon are started from the command line.
1243 // This means that this is executed by a PHP interpreter without runtime limitations
1244 if (function_exists('pcntl_fork') && in_array(DI::mode()->getExecutor(), [Mode::DAEMON, Mode::WORKER])) {
1245 self::forkProcess($do_cron);
1247 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1248 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1249 $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1252 // after spawning we have to remove the flag.
1253 if (self::isDaemonMode()) {
1254 self::IPCSetJobState(false);
1259 * Adds tasks to the worker queue
1261 * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1263 * next args are passed as $cmd command line
1264 * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1265 * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1267 * @return boolean "false" if worker queue entry already existed or there had been an error
1268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1269 * @note $cmd and string args are surrounded with ""
1275 public static function add($cmd)
1277 $args = func_get_args();
1279 if (!count($args)) {
1283 $arr = ['args' => $args, 'run_cmd' => true];
1285 Hook::callAll("proc_run", $arr);
1286 if (!$arr['run_cmd'] || !count($args)) {
1290 $priority = PRIORITY_MEDIUM;
1291 // Don't fork from frontend tasks by default
1292 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1293 $created = DateTimeFormat::utcNow();
1294 $delayed = DBA::NULL_DATETIME;
1295 $force_priority = false;
1297 $run_parameter = array_shift($args);
1299 if (is_int($run_parameter)) {
1300 $priority = $run_parameter;
1301 } elseif (is_array($run_parameter)) {
1302 if (isset($run_parameter['delayed'])) {
1303 $delayed = $run_parameter['delayed'];
1305 if (isset($run_parameter['priority'])) {
1306 $priority = $run_parameter['priority'];
1308 if (isset($run_parameter['created'])) {
1309 $created = $run_parameter['created'];
1311 if (isset($run_parameter['dont_fork'])) {
1312 $dont_fork = $run_parameter['dont_fork'];
1314 if (isset($run_parameter['force_priority'])) {
1315 $force_priority = $run_parameter['force_priority'];
1319 $command = array_shift($args);
1320 $parameters = json_encode($args);
1321 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1324 if (!in_array($priority, PRIORITIES)) {
1325 Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1326 $priority = PRIORITY_MEDIUM;
1329 // Quit if there was a database error - a precaution for the update process to 3.5.3
1330 if (DBA::errorNo() != 0) {
1335 $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1336 'priority' => $priority, 'next_try' => $delayed]);
1340 } elseif ($force_priority) {
1341 DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1344 // Set the IPC flag to ensure an immediate process execution via daemon
1345 if (self::isDaemonMode()) {
1346 self::IPCSetJobState(true);
1349 self::checkDaemonState();
1351 // Should we quit and wait for the worker to be called as a cronjob?
1356 // If there is a lock then we don't have to check for too much worker
1357 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1361 // If there are already enough workers running, don't fork another one
1362 $quit = self::tooMuchWorkers();
1363 DI::lock()->release(self::LOCK_WORKER);
1369 // Quit on daemon mode
1370 if (self::isDaemonMode()) {
1374 // Now call the worker to execute the jobs that we just added to the queue
1375 self::spawnWorker();
1380 public static function countWorkersByCommand(string $command)
1382 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1386 * Returns the next retrial level for worker jobs.
1387 * This function will skip levels when jobs are older.
1389 * @param array $queue Worker queue entry
1390 * @param integer $max_level maximum retrial level
1391 * @return integer the next retrial level value
1393 private static function getNextRetrial($queue, $max_level)
1395 $created = strtotime($queue['created']);
1396 $retrial_time = time() - $created;
1398 $new_retrial = $queue['retrial'] + 1;
1400 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1401 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1403 if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1404 $new_retrial = $retrial;
1407 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1408 return $new_retrial;
1412 * Defers the current worker entry
1414 * @return boolean had the entry been deferred?
1416 public static function defer()
1418 if (empty(DI::app()->queue)) {
1422 $queue = DI::app()->queue;
1424 $retrial = $queue['retrial'];
1426 $priority = $queue['priority'];
1428 $max_level = DI::config()->get('system', 'worker_defer_limit');
1430 $new_retrial = self::getNextRetrial($queue, $max_level);
1432 if ($new_retrial > $max_level) {
1433 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]);
1437 // Calculate the delay until the next trial
1438 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1439 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1441 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1442 $priority = PRIORITY_MEDIUM;
1443 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1444 $priority = PRIORITY_LOW;
1445 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1446 $priority = PRIORITY_NEGLIGIBLE;
1449 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1451 $stamp = (float)microtime(true);
1452 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1453 DBA::update('workerqueue', $fields, ['id' => $id]);
1454 self::$db_duration += (microtime(true) - $stamp);
1455 self::$db_duration_write += (microtime(true) - $stamp);
1461 * Set the flag if some job is waiting
1463 * @param boolean $jobs Is there a waiting job?
1464 * @throws \Exception
1466 public static function IPCSetJobState($jobs)
1468 $stamp = (float)microtime(true);
1469 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1470 self::$db_duration += (microtime(true) - $stamp);
1471 self::$db_duration_write += (microtime(true) - $stamp);
1475 * Checks if some worker job waits to be executed
1478 * @throws \Exception
1480 public static function IPCJobsExists()
1482 $stamp = (float)microtime(true);
1483 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1484 self::$db_duration += (microtime(true) - $stamp);
1486 // When we don't have a row, no job is running
1487 if (!DBA::isResult($row)) {
1491 return (bool)$row['jobs'];
1495 * Checks if the worker is running in the daemon mode.
1499 public static function isDaemonMode()
1501 if (!is_null(self::$daemon_mode)) {
1502 return self::$daemon_mode;
1505 if (DI::mode()->getExecutor() == Mode::DAEMON) {
1509 $daemon_mode = DI::config()->get('system', 'worker_daemon_mode', false, true);
1511 return $daemon_mode;
1514 $pidfile = DI::config()->get('system', 'pidfile');
1515 if (empty($pidfile)) {
1516 // No pid file, no daemon
1517 self::$daemon_mode = false;
1521 if (!is_readable($pidfile)) {
1522 // No pid file. We assume that the daemon had been intentionally stopped.
1523 self::$daemon_mode = false;
1527 $pid = intval(file_get_contents($pidfile));
1528 $running = posix_kill($pid, 0);
1530 self::$daemon_mode = $running;
1535 * Test if the daemon is running. If not, it will be started
1539 private static function checkDaemonState()
1541 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1545 if (!DI::mode()->isNormal()) {
1549 // Check every minute if the daemon is running
1550 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1554 DI::config()->set('system', 'last_daemon_check', time());
1556 $pidfile = DI::config()->get('system', 'pidfile');
1557 if (empty($pidfile)) {
1558 // No pid file, no daemon
1562 if (!is_readable($pidfile)) {
1563 // No pid file. We assume that the daemon had been intentionally stopped.
1567 $pid = intval(file_get_contents($pidfile));
1568 if (posix_kill($pid, 0)) {
1569 Logger::info('Daemon process is running', ['pid' => $pid]);
1573 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1575 self::spawnDaemon();
1579 * Spawn a new daemon process
1583 private static function spawnDaemon()
1585 Logger::notice('Starting new daemon process');
1586 $command = 'bin/daemon.php';
1588 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1589 $process->run($command, ['start']);
1590 Logger::notice('New daemon process started');
1594 * Check if the system is inside the defined maintenance window
1598 public static function isInMaintenanceWindow(bool $check_last_execution = false)
1600 // Calculate the seconds of the start end end of the maintenance window
1601 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1602 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1604 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1606 if ($check_last_execution) {
1607 // Calculate the window duration
1608 $duration = max($start, $end) - min($start, $end);
1610 // Quit when the last cron execution had been after the previous window
1611 $last_cron = DI::config()->get('system', 'last_cron_daily');
1612 if ($last_cron + $duration > time()) {
1613 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)]);
1618 $current = time() % 86400;
1620 if ($start < $end) {
1621 // Execute if we are inside the window
1622 $execute = ($current >= $start) && ($current <= $end);
1624 // Don't execute if we are outside the window
1625 $execute = !(($current > $end) && ($current < $start));
1629 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)]);
1631 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)]);