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