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