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