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