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