]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
More cooldown calls for worker processes
[friendica.git] / src / Core / Worker.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\Core\Worker\Entity\Process;
25 use Friendica\Database\DBA;
26 use Friendica\DI;
27 use Friendica\Util\DateTimeFormat;
28
29 /**
30  * Contains the class for the worker background job processing
31  */
32 class Worker
33 {
34         const STATE_STARTUP    = 1; // Worker is in startup. This takes most time.
35         const STATE_LONG_LOOP  = 2; // Worker is processing the whole - long - loop.
36         const STATE_REFETCH    = 3; // Worker had refetched jobs in the execution loop.
37         const STATE_SHORT_LOOP = 4; // Worker is processing preassigned jobs, thus saving much time.
38
39         const FAST_COMMANDS = ['APDelivery', 'Delivery'];
40
41         const LOCK_PROCESS = 'worker_process';
42         const LOCK_WORKER = 'worker';
43
44         private static $up_start;
45         private static $db_duration = 0;
46         private static $db_duration_count = 0;
47         private static $db_duration_write = 0;
48         private static $db_duration_stat = 0;
49         private static $lock_duration = 0;
50         private static $last_update;
51         private static $state;
52         /** @var Process */
53         private static $process;
54
55         /**
56          * Processes the tasks that are in the workerqueue table
57          *
58          * @param boolean $run_cron Should the cron processes be executed?
59          * @param Process $process  The current running process
60          * @return void
61          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62          */
63         public static function processQueue(bool $run_cron, Process $process)
64         {
65                 self::$up_start = microtime(true);
66
67                 // At first check the maximum load. We shouldn't continue with a high load
68                 if (DI::system()->isMaxLoadReached()) {
69                         Logger::notice('Pre check: maximum load reached, quitting.');
70                         return;
71                 }
72
73                 // We now start the process. This is done after the load check since this could increase the load.
74                 self::$process = $process;
75
76                 // Kill stale processes every 5 minutes
77                 $last_cleanup = DI::config()->get('system', 'worker_last_cleaned', 0);
78                 if (time() > ($last_cleanup + 300)) {
79                         DI::config()->set('system', 'worker_last_cleaned', time());
80                         Worker\Cron::killStaleWorkers();
81                 }
82
83                 // Check if the system is ready
84                 if (!self::isReady()) {
85                         return;
86                 }
87
88                 // Now we start additional cron processes if we should do so
89                 if ($run_cron) {
90                         Worker\Cron::run();
91                 }
92
93                 $last_check = $starttime = time();
94                 self::$state = self::STATE_STARTUP;
95
96                 // We fetch the next queue entry that is about to be executed
97                 while ($r = self::workerProcess()) {
98                         if (Worker\IPC::JobsExists(getmypid())) {
99                                 Worker\IPC::DeleteJobState(getmypid());
100                         }
101
102                         // Don't refetch when a worker fetches tasks for multiple workers
103                         $refetched = DI::config()->get('system', 'worker_multiple_fetch');
104                         foreach ($r as $entry) {
105                                 // The work will be done
106                                 if (!self::execute($entry)) {
107                                         Logger::warning('Process execution failed, quitting.', ['entry' => $entry]);
108                                         return;
109                                 }
110
111                                 // Trying to fetch new processes - but only once when successful
112                                 if (!$refetched && DI::lock()->acquire(self::LOCK_PROCESS, 0)) {
113                                         self::findWorkerProcesses();
114                                         DI::lock()->release(self::LOCK_PROCESS);
115                                         self::$state = self::STATE_REFETCH;
116                                         $refetched = true;
117                                 } else {
118                                         self::$state = self::STATE_SHORT_LOOP;
119                                 }
120                         }
121
122                         // To avoid the quitting of multiple workers only one worker at a time will execute the check
123                         if ((time() > $last_check + 5) && !self::getWaitingJobForPID()) {
124                                 self::$state = self::STATE_LONG_LOOP;
125
126                                 if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
127                                 // Count active workers and compare them with a maximum value that depends on the load
128                                         if (self::tooMuchWorkers()) {
129                                                 Logger::notice('Active worker limit reached, quitting.');
130                                                 DI::lock()->release(self::LOCK_WORKER);
131                                                 return;
132                                         }
133
134                                         // Check free memory
135                                         if (DI::system()->isMinMemoryReached()) {
136                                                 Logger::warning('Memory limit reached, quitting.');
137                                                 DI::lock()->release(self::LOCK_WORKER);
138                                                 return;
139                                         }
140                                         DI::lock()->release(self::LOCK_WORKER);
141                                 }
142                                 $last_check = time();
143                         }
144
145                         // Quit the worker once every cron interval
146                         if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60))) {
147                                 Logger::info('Process lifetime reached, respawning.');
148                                 self::unclaimProcess($process);
149                                 if (Worker\Daemon::isMode()) {
150                                         Worker\IPC::SetJobState(true);
151                                 } else {
152                                         self::spawnWorker();
153                                 }
154                                 return;
155                         }
156                 }
157
158                 // Cleaning up. Possibly not needed, but it doesn't harm anything.
159                 if (Worker\Daemon::isMode()) {
160                         Worker\IPC::SetJobState(false);
161                 }
162                 Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
163         }
164
165         /**
166          * Checks if the system is ready.
167          *
168          * Several system parameters like memory, connections and processes are checked.
169          *
170          * @return boolean
171          */
172         public static function isReady(): bool
173         {
174                 // Count active workers and compare them with a maximum value that depends on the load
175                 if (self::tooMuchWorkers()) {
176                         Logger::notice('Active worker limit reached, quitting.');
177                         return false;
178                 }
179
180                 // Do we have too few memory?
181                 if (DI::system()->isMinMemoryReached()) {
182                         Logger::warning('Memory limit reached, quitting.');
183                         return false;
184                 }
185
186                 // Possibly there are too much database connections
187                 if (self::maxConnectionsReached()) {
188                         Logger::warning('Maximum connections reached, quitting.');
189                         return false;
190                 }
191
192                 // Possibly there are too much database processes that block the system
193                 if (DI::system()->isMaxProcessesReached()) {
194                         Logger::warning('Maximum processes reached, quitting.');
195                         return false;
196                 }
197
198                 return true;
199         }
200
201         /**
202          * Check if non executed tasks do exist in the worker queue
203          *
204          * @return boolean Returns "true" if tasks are existing
205          * @throws \Exception
206          */
207         public static function entriesExists(): bool
208         {
209                 $stamp = (float)microtime(true);
210                 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
211                 self::$db_duration += (microtime(true) - $stamp);
212                 return $exists;
213         }
214
215         /**
216          * Returns the number of deferred entries in the worker queue
217          *
218          * @return integer Number of deferred entries in the worker queue
219          * @throws \Exception
220          */
221         private static function deferredEntries(): int
222         {
223                 $stamp = (float)microtime(true);
224                 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
225                 self::$db_duration += (microtime(true) - $stamp);
226                 self::$db_duration_count += (microtime(true) - $stamp);
227                 return $count;
228         }
229
230         /**
231          * Returns the number of non executed entries in the worker queue
232          *
233          * @return integer Number of non executed entries in the worker queue
234          * @throws \Exception
235          */
236         private static function totalEntries(): int
237         {
238                 $stamp = (float)microtime(true);
239                 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
240                 self::$db_duration += (microtime(true) - $stamp);
241                 self::$db_duration_count += (microtime(true) - $stamp);
242                 return $count;
243         }
244
245         /**
246          * Returns the highest priority in the worker queue that isn't executed
247          *
248          * @return integer Number of active worker processes
249          * @throws \Exception
250          */
251         private static function highestPriority(): int
252         {
253                 $stamp = (float)microtime(true);
254                 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
255                 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
256                 self::$db_duration += (microtime(true) - $stamp);
257                 if (DBA::isResult($workerqueue)) {
258                         return $workerqueue['priority'];
259                 } else {
260                         return 0;
261                 }
262         }
263
264         /**
265          * Returns if a process with the given priority is running
266          *
267          * @param integer $priority The priority that should be checked
268          *
269          * @return integer Is there a process running with that priority?
270          * @throws \Exception
271          */
272         private static function processWithPriorityActive(int $priority): int
273         {
274                 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
275                 return DBA::exists('workerqueue', $condition);
276         }
277
278         /**
279          * Checks if the given file is valid to be included
280          *
281          * @param mixed $file
282          * @return bool
283          */
284         private static function validateInclude(&$file): bool
285         {
286                 $orig_file = $file;
287
288                 $file = realpath($file);
289
290                 if (strpos($file, getcwd()) !== 0) {
291                         return false;
292                 }
293
294                 $file = str_replace(getcwd() . '/', '', $file, $count);
295                 if ($count != 1) {
296                         return false;
297                 }
298
299                 if ($orig_file !== $file) {
300                         return false;
301                 }
302
303                 $valid = false;
304                 if (strpos($file, 'include/') === 0) {
305                         $valid = true;
306                 }
307
308                 if (strpos($file, 'addon/') === 0) {
309                         $valid = true;
310                 }
311
312                 // Simply return flag
313                 return $valid;
314         }
315
316         /**
317          * Execute a worker entry
318          *
319          * @param array $queue Workerqueue entry
320          *
321          * @return boolean "true" if further processing should be stopped
322          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323          */
324         public static function execute(array $queue): bool
325         {
326                 $mypid = getmypid();
327
328                 // Quit when in maintenance
329                 if (DI::config()->get('system', 'maintenance', false, true)) {
330                         Logger::notice('Maintenance mode - quit process', ['pid' => $mypid]);
331                         return false;
332                 }
333
334                 // Constantly check the number of parallel database processes
335                 if (DI::system()->isMaxProcessesReached()) {
336                         Logger::warning('Max processes reached for process', ['pid' => $mypid]);
337                         return false;
338                 }
339
340                 // Constantly check the number of available database connections to let the frontend be accessible at any time
341                 if (self::maxConnectionsReached()) {
342                         Logger::warning('Max connection reached for process', ['pid' => $mypid]);
343                         return false;
344                 }
345
346                 $argv = json_decode($queue['parameter'], true);
347                 if (!is_array($argv)) {
348                         $argv = [];
349                 }
350
351                 if (!empty($queue['command'])) {
352                         array_unshift($argv, $queue['command']);
353                 }
354
355                 if (empty($argv)) {
356                         Logger::warning('Parameter is empty', ['queue' => $queue]);
357                         return false;
358                 }
359
360                 // Check for existance and validity of the include file
361                 $include = $argv[0];
362
363                 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
364                         // We constantly update the "executed" date every minute to avoid being killed too soon
365                         if (!isset(self::$last_update)) {
366                                 self::$last_update = strtotime($queue['executed']);
367                         }
368
369                         $age = (time() - self::$last_update) / 60;
370                         self::$last_update = time();
371
372                         if ($age > 1) {
373                                 $stamp = (float)microtime(true);
374                                 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
375                                 self::$db_duration += (microtime(true) - $stamp);
376                                 self::$db_duration_write += (microtime(true) - $stamp);
377                         }
378
379                         array_shift($argv);
380
381                         self::execFunction($queue, $include, $argv, true);
382
383                         $stamp = (float)microtime(true);
384                         $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
385                         if (DBA::update('workerqueue', ['done' => true], $condition)) {
386                                 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
387                         }
388                         self::$db_duration = (microtime(true) - $stamp);
389                         self::$db_duration_write += (microtime(true) - $stamp);
390
391                         return true;
392                 }
393
394                 // The script could be provided as full path or only with the function name
395                 if ($include == basename($include)) {
396                         $include = 'include/' . $include . '.php';
397                 }
398
399                 if (!self::validateInclude($include)) {
400                         Logger::warning('Include file is not valid', ['file' => $argv[0]]);
401                         $stamp = (float)microtime(true);
402                         DBA::delete('workerqueue', ['id' => $queue['id']]);
403                         self::$db_duration = (microtime(true) - $stamp);
404                         self::$db_duration_write += (microtime(true) - $stamp);
405                         return true;
406                 }
407
408                 require_once $include;
409
410                 $funcname = str_replace('.php', '', basename($argv[0])) .'_run';
411
412                 if (function_exists($funcname)) {
413                         // We constantly update the "executed" date every minute to avoid being killed too soon
414                         if (!isset(self::$last_update)) {
415                                 self::$last_update = strtotime($queue['executed']);
416                         }
417
418                         $age = (time() - self::$last_update) / 60;
419                         self::$last_update = time();
420
421                         if ($age > 1) {
422                                 $stamp = (float)microtime(true);
423                                 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
424                                 self::$db_duration += (microtime(true) - $stamp);
425                                 self::$db_duration_write += (microtime(true) - $stamp);
426                         }
427
428                         self::execFunction($queue, $funcname, $argv, false);
429
430                         $stamp = (float)microtime(true);
431                         if (DBA::update('workerqueue', ['done' => true], ['id' => $queue['id']])) {
432                                 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
433                         }
434                         self::$db_duration = (microtime(true) - $stamp);
435                         self::$db_duration_write += (microtime(true) - $stamp);
436                 } else {
437                         Logger::warning('Function does not exist', ['function' => $funcname]);
438                         $stamp = (float)microtime(true);
439                         DBA::delete('workerqueue', ['id' => $queue['id']]);
440                         self::$db_duration = (microtime(true) - $stamp);
441                         self::$db_duration_write += (microtime(true) - $stamp);
442                 }
443
444                 return true;
445         }
446
447         /**
448          * Slow the execution down if the system load is too high
449          *
450          * @return void
451          */
452         public static function coolDown()
453         {
454                 $load_cooldown      = DI::config()->get('system', 'worker_load_cooldown');
455                 $processes_cooldown = DI::config()->get('system', 'worker_processes_cooldown');
456
457                 if (($load_cooldown == 0) && ($processes_cooldown == 0)) {
458                         return;
459                 }
460
461                 $sleeping = false;
462
463                 while ($load = System::getLoadAvg()) {
464                         if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) {
465                                 if (!$sleeping) {
466                                         Logger::notice('Load induced pre execution cooldown.', ['max' => $load_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
467                                         $sleeping = true;
468                                 }
469                                 sleep(1);
470                                 continue;
471                         }
472                         if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) {
473                                 if (!$sleeping) {
474                                         Logger::notice('Process induced pre execution cooldown.', ['max' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
475                                         $sleeping = true;
476                                 }
477                                 sleep(1);
478                                 continue;
479                         }
480                         break;
481                 }
482
483                 if ($sleeping) {
484                         Logger::notice('Cooldown ended.', ['max-load' => $load_cooldown, 'max-processes' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
485                 }
486         }
487
488         /**
489          * Execute a function from the queue
490          *
491          * @param array   $queue       Workerqueue entry
492          * @param string  $funcname    name of the function
493          * @param array   $argv        Array of values to be passed to the function
494          * @param boolean $method_call boolean
495          * @return void
496          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
497          */
498         private static function execFunction(array $queue, string $funcname, array $argv, bool $method_call)
499         {
500                 $a = DI::app();
501
502                 $cooldown = DI::config()->get('system', 'worker_cooldown', 0);
503                 if ($cooldown > 0) {
504                         Logger::notice('Pre execution cooldown.', ['cooldown' => $cooldown, 'id' => $queue['id'], 'priority' => $queue['priority'], 'command' => $queue['command']]);
505                         sleep($cooldown);
506                 }
507
508                 self::coolDown();
509
510                 Logger::enableWorker($funcname);
511
512                 Logger::info('Process start.', ['priority' => $queue['priority'], 'id' => $queue['id']]);
513
514                 $stamp = (float)microtime(true);
515
516                 // We use the callstack here to analyze the performance of executed worker entries.
517                 // For this reason the variables have to be initialized.
518                 DI::profiler()->reset();
519
520                 $a->setQueue($queue);
521
522                 $up_duration = microtime(true) - self::$up_start;
523
524                 // Reset global data to avoid interferences
525                 unset($_SESSION);
526
527                 // Set the workerLogger as new default logger
528                 if ($method_call) {
529                         call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
530                 } else {
531                         $funcname($argv, count($argv));
532                 }
533
534                 Logger::disableWorker();
535
536                 $a->setQueue([]);
537
538                 $duration = (microtime(true) - $stamp);
539
540                 /* With these values we can analyze how effective the worker is.
541                  * The database and rest time should be low since this is the unproductive time.
542                  * The execution time is the productive time.
543                  * By changing parameters like the maximum number of workers we can check the effectivness.
544                 */
545                 $dbtotal = round(self::$db_duration, 2);
546                 $dbread  = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
547                 $dbcount = round(self::$db_duration_count, 2);
548                 $dbstat  = round(self::$db_duration_stat, 2);
549                 $dbwrite = round(self::$db_duration_write, 2);
550                 $dblock  = round(self::$lock_duration, 2);
551                 $rest    = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
552                 $exec    = round($duration, 2);
553
554                 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
555
556                 self::coolDown();
557
558                 self::$up_start = microtime(true);
559                 self::$db_duration = 0;
560                 self::$db_duration_count = 0;
561                 self::$db_duration_stat = 0;
562                 self::$db_duration_write = 0;
563                 self::$lock_duration = 0;
564
565                 if ($duration > 3600) {
566                         Logger::info('Longer than 1 hour.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
567                 } elseif ($duration > 600) {
568                         Logger::info('Longer than 10 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
569                 } elseif ($duration > 300) {
570                         Logger::info('Longer than 5 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
571                 } elseif ($duration > 120) {
572                         Logger::info('Longer than 2 minutes.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration/60, 3)]);
573                 }
574
575                 Logger::info('Process done.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'duration' => round($duration, 3)]);
576
577                 DI::profiler()->saveLog(DI::logger(), 'ID ' . $queue['id'] . ': ' . $funcname);
578
579                 if ($cooldown > 0) {
580                         Logger::info('Post execution cooldown.', ['priority' => $queue['priority'], 'id' => $queue['id'], 'cooldown' => $cooldown]);
581                         sleep($cooldown);
582                 }
583         }
584
585         /**
586          * Checks if the number of database connections has reached a critical limit.
587          *
588          * @return bool Are more than 3/4 of the maximum connections used?
589          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
590          */
591         private static function maxConnectionsReached(): bool
592         {
593                 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
594                 $max = DI::config()->get('system', 'max_connections');
595
596                 // Fetch the percentage level where the worker will get active
597                 $maxlevel = DI::config()->get('system', 'max_connections_level', 75);
598
599                 if ($max == 0) {
600                         // the maximum number of possible user connections can be a system variable
601                         $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
602                         if (DBA::isResult($r)) {
603                                 $max = $r['Value'];
604                         }
605                         // Or it can be granted. This overrides the system variable
606                         $stamp = (float)microtime(true);
607                         $r = DBA::p('SHOW GRANTS');
608                         self::$db_duration += (microtime(true) - $stamp);
609                         while ($grants = DBA::fetch($r)) {
610                                 $grant = array_pop($grants);
611                                 if (stristr($grant, "GRANT USAGE ON")) {
612                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
613                                                 $max = $match[1];
614                                         }
615                                 }
616                         }
617                         DBA::close($r);
618                 }
619
620                 // If $max is set we will use the processlist to determine the current number of connections
621                 // The processlist only shows entries of the current user
622                 if ($max != 0) {
623                         $stamp = (float)microtime(true);
624                         $r = DBA::p('SHOW PROCESSLIST');
625                         self::$db_duration += (microtime(true) - $stamp);
626                         $used = DBA::numRows($r);
627                         DBA::close($r);
628
629                         Logger::info('Connection usage (user values)', ['usage' => $used, 'max' => $max]);
630
631                         $level = ($used / $max) * 100;
632
633                         if ($level >= $maxlevel) {
634                                 Logger::warning('Maximum level (' . $maxlevel . '%) of user connections reached: ' . $used .'/' . $max);
635                                 return true;
636                         }
637                 }
638
639                 // We will now check for the system values.
640                 // This limit could be reached although the user limits are fine.
641                 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
642                 if (!DBA::isResult($r)) {
643                         return false;
644                 }
645                 $max = intval($r['Value']);
646                 if ($max == 0) {
647                         return false;
648                 }
649                 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
650                 if (!DBA::isResult($r)) {
651                         return false;
652                 }
653                 $used = intval($r['Value']);
654                 if ($used == 0) {
655                         return false;
656                 }
657                 Logger::info('Connection usage (system values)', ['used' => $used, 'max' => $max]);
658
659                 $level = $used / $max * 100;
660
661                 if ($level < $maxlevel) {
662                         return false;
663                 }
664                 Logger::warning('Maximum level (' . $level . '%) of system connections reached: ' . $used . '/' . $max);
665                 return true;
666         }
667
668
669         /**
670          * Checks if the number of active workers exceeds the given limits
671          *
672          * @return bool Are there too much workers running?
673          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
674          */
675         private static function tooMuchWorkers(): bool
676         {
677                 $queues = DI::config()->get('system', 'worker_queues', 10);
678
679                 $maxqueues = $queues;
680
681                 $active = self::activeWorkers();
682
683                 // Decrease the number of workers at higher load
684                 $load = System::currentLoad();
685                 if ($load) {
686                         $maxsysload = intval(DI::config()->get('system', 'maxloadavg', 20));
687
688                         /* Default exponent 3 causes queues to rapidly decrease as load increases.
689                          * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
690                          * For some environments, this rapid decrease is not needed.
691                          * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
692                          */
693                         $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
694                         $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
695                         $queues = intval(ceil($slope * $maxqueues));
696
697                         $processlist = '';
698
699                         if (DI::config()->get('system', 'worker_jpm')) {
700                                 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
701                                 $jobs_per_minute = [];
702                                 foreach ($intervals as $interval) {
703                                         if ($interval == 0) {
704                                                 continue;
705                                         } else {
706                                                 $interval = (int)$interval;
707                                         }
708
709                                         $stamp = (float)microtime(true);
710                                         $jobs = DBA::count('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $interval . ' minute')]);
711                                         self::$db_duration += (microtime(true) - $stamp);
712                                         self::$db_duration_stat += (microtime(true) - $stamp);
713                                         $jobs_per_minute[$interval] = number_format($jobs / $interval, 0);
714                                 }
715                                 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
716                         }
717
718                         // Create a list of queue entries grouped by their priority
719                         $listitem = [0 => ''];
720
721                         $idle_workers = $active;
722
723                         $deferred = self::deferredEntries();
724
725                         if (DI::config()->get('system', 'worker_debug')) {
726                                 $waiting_processes = 0;
727                                 // Now adding all processes with workerqueue entries
728                                 $stamp = (float)microtime(true);
729                                 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
730                                 self::$db_duration += (microtime(true) - $stamp);
731                                 self::$db_duration_stat += (microtime(true) - $stamp);
732                                 while ($entry = DBA::fetch($jobs)) {
733                                         $stamp = (float)microtime(true);
734                                         $running = DBA::count('workerqueue-view', ['priority' => $entry['priority']]);
735                                         self::$db_duration += (microtime(true) - $stamp);
736                                         self::$db_duration_stat += (microtime(true) - $stamp);
737                                         $idle_workers -= $running;
738                                         $waiting_processes += $entry['entries'];
739                                         $listitem[$entry['priority']] = $entry['priority'] . ':' . $running . '/' . $entry['entries'];
740                                 }
741                                 DBA::close($jobs);
742                         } else {
743                                 $waiting_processes =  self::totalEntries();
744                                 $stamp = (float)microtime(true);
745                                 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
746                                 self::$db_duration += (microtime(true) - $stamp);
747                                 self::$db_duration_stat += (microtime(true) - $stamp);
748
749                                 while ($entry = DBA::fetch($jobs)) {
750                                         $idle_workers -= $entry['running'];
751                                         $listitem[$entry['priority']] = $entry['priority'] . ':' . $entry['running'];
752                                 }
753                                 DBA::close($jobs);
754                         }
755
756                         $waiting_processes -= $deferred;
757
758                         $listitem[0] = '0:' . max(0, $idle_workers);
759
760                         $processlist .= ' ('.implode(', ', $listitem).')';
761
762                         if (DI::config()->get('system', 'worker_fastlane', false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
763                                 $top_priority = self::highestPriority();
764                                 $high_running = self::processWithPriorityActive($top_priority);
765
766                                 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
767                                         Logger::info('Jobs with a higher priority are waiting but none is executed. Open a fastlane.', ['priority' => $top_priority]);
768                                         $queues = $active + 1;
769                                 }
770                         }
771
772                         Logger::notice('Load: ' . $load . '/' . $maxsysload . ' - processes: ' . $deferred . '/' . $active . '/' . $waiting_processes . $processlist . ' - maximum: ' . $queues . '/' . $maxqueues);
773
774                         // Are there fewer workers running as possible? Then fork a new one.
775                         if (!DI::config()->get('system', 'worker_dont_fork', false) && ($queues > ($active + 1)) && self::entriesExists()) {
776                                 Logger::info('There are fewer workers as possible, fork a new worker.', ['active' => $active, 'queues' => $queues]);
777                                 if (Worker\Daemon::isMode()) {
778                                         Worker\IPC::SetJobState(true);
779                                 } else {
780                                         self::spawnWorker();
781                                 }
782                         }
783                 }
784
785                 // if there are too much worker, we don't spawn a new one.
786                 if (Worker\Daemon::isMode() && ($active > $queues)) {
787                         Worker\IPC::SetJobState(false);
788                 }
789
790                 return $active > $queues;
791         }
792
793         /**
794          * Returns the number of active worker processes
795          *
796          * @return integer Number of active worker processes
797          * @throws \Exception
798          */
799         private static function activeWorkers(): int
800         {
801                 $stamp = (float)microtime(true);
802                 $count = DI::process()->countCommand('Worker.php');
803                 self::$db_duration += (microtime(true) - $stamp);
804                 self::$db_duration_count += (microtime(true) - $stamp);
805                 return $count;
806         }
807
808         /**
809          * Returns the number of active worker processes
810          *
811          * @return array List of worker process ids
812          * @throws \Exception
813          */
814         private static function getWorkerPIDList(): array
815         {
816                 $ids = [];
817                 $stamp = (float)microtime(true);
818
819                 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
820                         LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done`
821                         GROUP BY `process`.`pid`");
822                 while ($queue = DBA::fetch($queues)) {
823                         $ids[$queue['pid']] = $queue['entries'];
824                 }
825                 DBA::close($queues);
826
827                 self::$db_duration += (microtime(true) - $stamp);
828                 self::$db_duration_count += (microtime(true) - $stamp);
829                 return $ids;
830         }
831
832         /**
833          * Returns waiting jobs for the current process id
834          *
835          * @return array|bool waiting workerqueue jobs or FALSE on failture
836          * @throws \Exception
837          */
838         private static function getWaitingJobForPID()
839         {
840                 $stamp = (float)microtime(true);
841                 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
842                 self::$db_duration += (microtime(true) - $stamp);
843                 if (DBA::isResult($r)) {
844                         return DBA::toArray($r);
845                 }
846                 DBA::close($r);
847
848                 return false;
849         }
850
851         /**
852          * Returns the next jobs that should be executed
853          * @param int $limit
854          * @return array array with next jobs
855          * @throws \Exception
856          */
857         private static function nextProcess(int $limit): array
858         {
859                 $priority = self::nextPriority();
860                 if (empty($priority)) {
861                         Logger::info('No tasks found');
862                         return [];
863                 }
864
865                 $ids = [];
866                 $stamp = (float)microtime(true);
867                 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
868                 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
869                 self::$db_duration += (microtime(true) - $stamp);
870                 while ($task = DBA::fetch($tasks)) {
871                         $ids[] = $task['id'];
872                         // Only continue that loop while we are storing commands that can be processed quickly
873                         if (!empty($task['command'])) {
874                                 $command = $task['command'];
875                         } else {
876                                 $command = json_decode($task['parameter'])[0];
877                         }
878
879                         if (!in_array($command, self::FAST_COMMANDS)) {
880                                 break;
881                         }
882                 }
883                 DBA::close($tasks);
884
885                 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
886                 return $ids;
887         }
888
889         /**
890          * Returns the priority of the next workerqueue job
891          *
892          * @return string|bool priority or FALSE on failure
893          * @throws \Exception
894          */
895         private static function nextPriority()
896         {
897                 $waiting = [];
898                 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
899                 foreach ($priorities as $priority) {
900                         $stamp = (float)microtime(true);
901                         if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
902                                 $waiting[$priority] = true;
903                         }
904                         self::$db_duration += (microtime(true) - $stamp);
905                 }
906
907                 if (!empty($waiting[PRIORITY_CRITICAL])) {
908                         return PRIORITY_CRITICAL;
909                 }
910
911                 $running = [];
912                 $running_total = 0;
913                 $stamp = (float)microtime(true);
914                 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
915                 self::$db_duration += (microtime(true) - $stamp);
916                 while ($process = DBA::fetch($processes)) {
917                         $running[$process['priority']] = $process['running'];
918                         $running_total += $process['running'];
919                 }
920                 DBA::close($processes);
921
922                 foreach ($priorities as $priority) {
923                         if (!empty($waiting[$priority]) && empty($running[$priority])) {
924                                 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
925                                 return $priority;
926                         }
927                 }
928
929                 $active = max(self::activeWorkers(), $running_total);
930                 $priorities = max(count($waiting), count($running));
931                 $exponent = 2;
932
933                 $total = 0;
934                 for ($i = 1; $i <= $priorities; ++$i) {
935                         $total += pow($i, $exponent);
936                 }
937
938                 $limit = [];
939                 for ($i = 1; $i <= $priorities; ++$i) {
940                         $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
941                 }
942
943                 $i = 0;
944                 foreach ($running as $priority => $workers) {
945                         if ($workers < $limit[$i++]) {
946                                 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
947                                 return $priority;
948                         }
949                 }
950
951                 if (!empty($waiting)) {
952                         $priority = array_keys($waiting)[0];
953                         Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
954                         return $priority;
955                 }
956
957                 return false;
958         }
959
960         /**
961          * Find and claim the next worker process for us
962          *
963          * @return void
964          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
965          */
966         private static function findWorkerProcesses()
967         {
968                 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
969
970                 if (DI::config()->get('system', 'worker_multiple_fetch')) {
971                         $pids = [];
972                         foreach (self::getWorkerPIDList() as $pid => $count) {
973                                 if ($count <= $fetch_limit) {
974                                         $pids[] = $pid;
975                                 }
976                         }
977                         if (empty($pids)) {
978                                 return;
979                         }
980                         $limit = $fetch_limit * count($pids);
981                 } else {
982                         $pids = [getmypid()];
983                         $limit = $fetch_limit;
984                 }
985
986                 $ids = self::nextProcess($limit);
987                 $limit -= count($ids);
988
989                 // If there is not enough results we check without priority limit
990                 if ($limit > 0) {
991                         $stamp = (float)microtime(true);
992                         $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
993                         $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
994                         self::$db_duration += (microtime(true) - $stamp);
995
996                         while ($task = DBA::fetch($tasks)) {
997                                 $ids[] = $task['id'];
998                                 // Only continue that loop while we are storing commands that can be processed quickly
999                                 if (!empty($task['command'])) {
1000                                         $command = $task['command'];
1001                                 } else {
1002                                         $command = json_decode($task['parameter'])[0];
1003                                 }
1004                                 if (!in_array($command, self::FAST_COMMANDS)) {
1005                                         break;
1006                                 }
1007                         }
1008                         DBA::close($tasks);
1009                 }
1010
1011                 if (empty($ids)) {
1012                         return;
1013                 }
1014
1015                 // Assign the task ids to the workers
1016                 $worker = [];
1017                 foreach (array_unique($ids) as $id) {
1018                         $pid = next($pids);
1019                         if (!$pid) {
1020                                 $pid = reset($pids);
1021                         }
1022                         $worker[$pid][] = $id;
1023                 }
1024
1025                 $stamp = (float)microtime(true);
1026                 foreach ($worker as $worker_pid => $worker_ids) {
1027                         Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1028                         DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1029                                 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1030                 }
1031                 self::$db_duration += (microtime(true) - $stamp);
1032                 self::$db_duration_write += (microtime(true) - $stamp);
1033         }
1034
1035         /**
1036          * Returns the next worker process
1037          *
1038          * @return array worker processes
1039          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1040          */
1041         public static function workerProcess(): array
1042         {
1043                 // There can already be jobs for us in the queue.
1044                 $waiting = self::getWaitingJobForPID();
1045                 if (!empty($waiting)) {
1046                         return $waiting;
1047                 }
1048
1049                 $stamp = (float)microtime(true);
1050                 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1051                         return [];
1052                 }
1053                 self::$lock_duration += (microtime(true) - $stamp);
1054
1055                 self::findWorkerProcesses();
1056
1057                 DI::lock()->release(self::LOCK_PROCESS);
1058
1059                 // Prevents "Return value of Friendica\Core\Worker::workerProcess() must be of the type array, bool returned"
1060                 $process = self::getWaitingJobForPID();
1061                 return (is_array($process) ? $process : []);
1062         }
1063
1064         /**
1065          * Removes a workerqueue entry from the current process
1066          *
1067          * @param Process $process the process behind the workerqueue
1068          *
1069          * @return void
1070          * @throws \Exception
1071          */
1072         public static function unclaimProcess(Process $process)
1073         {
1074                 $stamp = (float)microtime(true);
1075                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $process->pid, 'done' => false]);
1076                 self::$db_duration += (microtime(true) - $stamp);
1077                 self::$db_duration_write += (microtime(true) - $stamp);
1078         }
1079
1080         /**
1081          * Fork a child process
1082          *
1083          * @param boolean $do_cron
1084          * @return void
1085          */
1086         private static function forkProcess(bool $do_cron)
1087         {
1088                 if (DI::system()->isMinMemoryReached()) {
1089                         Logger::warning('Memory limit reached - quitting');
1090                         return;
1091                 }
1092
1093                 // Children inherit their parent's database connection.
1094                 // To avoid problems we disconnect and connect both parent and child
1095                 DBA::disconnect();
1096                 $pid = pcntl_fork();
1097                 if ($pid == -1) {
1098                         DBA::connect();
1099                         Logger::warning('Could not spawn worker');
1100                         return;
1101                 } elseif ($pid) {
1102                         // The parent process continues here
1103                         DBA::connect();
1104
1105                         Worker\IPC::SetJobState(true, $pid);
1106                         Logger::info('Spawned new worker', ['pid' => $pid]);
1107
1108                         $cycles = 0;
1109                         while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) {
1110                                 usleep(10000);
1111                         }
1112
1113                         Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
1114                         return;
1115                 }
1116
1117                 // We now are in the new worker
1118                 DBA::connect();
1119
1120                 DI::flushLogger();
1121                 $process = DI::process()->create(getmypid(), basename(__FILE__));
1122
1123                 $cycles = 0;
1124                 while (!Worker\IPC::JobsExists($process->pid) && (++$cycles < 100)) {
1125                         usleep(10000);
1126                 }
1127
1128                 Logger::info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]);
1129
1130                 self::processQueue($do_cron, $process);
1131
1132                 self::unclaimProcess($process);
1133
1134                 Worker\IPC::SetJobState(false, $process->pid);
1135                 DI::process()->delete($process);
1136                 Logger::info('Worker ended', ['pid' => $process->pid]);
1137                 exit();
1138         }
1139
1140         /**
1141          * Spawns a new worker
1142          *
1143          * @param bool $do_cron
1144          * @return void
1145          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1146          */
1147         public static function spawnWorker(bool $do_cron = false)
1148         {
1149                 if (Worker\Daemon::isMode() && DI::config()->get('system', 'worker_fork')) {
1150                         self::forkProcess($do_cron);
1151                 } else {
1152                         DI::system()->run('bin/worker.php', ['no_cron' => !$do_cron]);
1153                 }
1154                 if (Worker\Daemon::isMode()) {
1155                         Worker\IPC::SetJobState(false);
1156                 }
1157         }
1158
1159         /**
1160          * Adds tasks to the worker queue
1161          *
1162          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1163          *
1164          * next args are passed as $cmd command line
1165          * or: Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::DELETION, $drop_id);
1166          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), 'Delivery', $post_id);
1167          *
1168          * @return int '0' if worker queue entry already existed or there had been an error, otherwise the ID of the worker task
1169          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1170          * @note $cmd and string args are surrounded with ''
1171          *
1172          * @hooks 'proc_run'
1173          *    array $arr
1174          *
1175          */
1176         public static function add(...$args)
1177         {
1178                 if (!count($args)) {
1179                         return 0;
1180                 }
1181
1182                 $arr = ['args' => $args, 'run_cmd' => true];
1183
1184                 Hook::callAll('proc_run', $arr);
1185                 if (!$arr['run_cmd'] || !count($args)) {
1186                         return 1;
1187                 }
1188
1189                 $priority = PRIORITY_MEDIUM;
1190                 // Don't fork from frontend tasks by default
1191                 $dont_fork = DI::config()->get('system', 'worker_dont_fork', false) || !DI::mode()->isBackend();
1192                 $created = DateTimeFormat::utcNow();
1193                 $delayed = DBA::NULL_DATETIME;
1194                 $force_priority = false;
1195
1196                 $run_parameter = array_shift($args);
1197
1198                 if (is_int($run_parameter)) {
1199                         $priority = $run_parameter;
1200                 } elseif (is_array($run_parameter)) {
1201                         if (isset($run_parameter['delayed'])) {
1202                                 $delayed = $run_parameter['delayed'];
1203                         }
1204                         if (isset($run_parameter['priority'])) {
1205                                 $priority = $run_parameter['priority'];
1206                         }
1207                         if (isset($run_parameter['created'])) {
1208                                 $created = $run_parameter['created'];
1209                         }
1210                         if (isset($run_parameter['dont_fork'])) {
1211                                 $dont_fork = $run_parameter['dont_fork'];
1212                         }
1213                         if (isset($run_parameter['force_priority'])) {
1214                                 $force_priority = $run_parameter['force_priority'];
1215                         }
1216                 } else {
1217                         throw new \InvalidArgumentException('Priority number or task parameter array expected as first argument');
1218                 }
1219
1220                 $command = array_shift($args);
1221                 $parameters = json_encode($args);
1222                 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1223                 $added = 0;
1224
1225                 if (!is_int($priority) || !in_array($priority, PRIORITIES)) {
1226                         Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1227                         $priority = PRIORITY_MEDIUM;
1228                 }
1229
1230                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1231                 if (DBA::errorNo() != 0) {
1232                         return 0;
1233                 }
1234
1235                 if (!$found) {
1236                         if (!DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1237                                 'priority' => $priority, 'next_try' => $delayed])) {
1238                                 return 0;
1239                         }
1240                         $added = DBA::lastInsertId();
1241                 } elseif ($force_priority) {
1242                         DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1243                 }
1244
1245                 // Set the IPC flag to ensure an immediate process execution via daemon
1246                 if (Worker\Daemon::isMode()) {
1247                         Worker\IPC::SetJobState(true);
1248                 }
1249
1250                 Worker\Daemon::checkState();
1251
1252                 // Should we quit and wait for the worker to be called as a cronjob?
1253                 if ($dont_fork) {
1254                         return $added;
1255                 }
1256
1257                 // If there is a lock then we don't have to check for too much worker
1258                 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1259                         return $added;
1260                 }
1261
1262                 // If there are already enough workers running, don't fork another one
1263                 $quit = self::tooMuchWorkers();
1264                 DI::lock()->release(self::LOCK_WORKER);
1265
1266                 if ($quit) {
1267                         return $added;
1268                 }
1269
1270                 // Quit on daemon mode
1271                 if (Worker\Daemon::isMode()) {
1272                         return $added;
1273                 }
1274
1275                 // Now call the worker to execute the jobs that we just added to the queue
1276                 self::spawnWorker();
1277
1278                 return $added;
1279         }
1280
1281         public static function countWorkersByCommand(string $command): int
1282         {
1283                 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1284         }
1285
1286         /**
1287          * Returns the next retrial level for worker jobs.
1288          * This function will skip levels when jobs are older.
1289          *
1290          * @param array $queue Worker queue entry
1291          * @param integer $max_level maximum retrial level
1292          * @return integer the next retrial level value
1293          */
1294         private static function getNextRetrial(array $queue, int $max_level): int
1295         {
1296                 $created = strtotime($queue['created']);
1297                 $retrial_time = time() - $created;
1298
1299                 $new_retrial = $queue['retrial'] + 1;
1300                 $total = 0;
1301                 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1302                         $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1303                         $total += $delay;
1304                         if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1305                                 $new_retrial = $retrial;
1306                         }
1307                 }
1308                 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1309                 return $new_retrial;
1310         }
1311
1312         /**
1313          * Defers the current worker entry
1314          *
1315          * @return boolean had the entry been deferred?
1316          * @throws \Exception
1317          */
1318         public static function defer(): bool
1319         {
1320                 $queue = DI::app()->getQueue();
1321
1322                 if (empty($queue)) {
1323                         return false;
1324                 }
1325
1326                 $id = $queue['id'];
1327                 $priority = $queue['priority'];
1328
1329                 $max_level = DI::config()->get('system', 'worker_defer_limit');
1330
1331                 $new_retrial = self::getNextRetrial($queue, $max_level);
1332
1333                 if ($new_retrial > $max_level) {
1334                         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]);
1335                         return false;
1336                 }
1337
1338                 // Calculate the delay until the next trial
1339                 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1340                 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1341
1342                 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1343                         $priority = PRIORITY_MEDIUM;
1344                 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1345                         $priority = PRIORITY_LOW;
1346                 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1347                         $priority = PRIORITY_NEGLIGIBLE;
1348                 }
1349
1350                 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1351
1352                 $stamp = (float)microtime(true);
1353                 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1354                 DBA::update('workerqueue', $fields, ['id' => $id]);
1355                 self::$db_duration += (microtime(true) - $stamp);
1356                 self::$db_duration_write += (microtime(true) - $stamp);
1357
1358                 return true;
1359         }
1360
1361         /**
1362          * Check if the system is inside the defined maintenance window
1363          *
1364          * @param bool $check_last_execution Whether check last execution
1365          * @return boolean
1366          */
1367         public static function isInMaintenanceWindow(bool $check_last_execution = false): bool
1368         {
1369                 // Calculate the seconds of the start end end of the maintenance window
1370                 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1371                 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1372
1373                 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1374
1375                 if ($check_last_execution) {
1376                         // Calculate the window duration
1377                         $duration = max($start, $end) - min($start, $end);
1378
1379                         // Quit when the last cron execution had been after the previous window
1380                         $last_cron = DI::config()->get('system', 'last_cron_daily');
1381                         if ($last_cron + $duration > time()) {
1382                                 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)]);
1383                                 return false;
1384                         }
1385                 }
1386
1387                 $current = time() % 86400;
1388
1389                 if ($start < $end) {
1390                         // Execute if we are inside the window
1391                         $execute = ($current >= $start) && ($current <= $end);
1392                 } else {
1393                         // Don't execute if we are outside the window
1394                         $execute = !(($current > $end) && ($current < $start));
1395                 }
1396
1397                 if ($execute) {
1398                         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)]);
1399                 } else {
1400                         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)]);
1401                 }
1402
1403                 return $execute;
1404         }
1405 }