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