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