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