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