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