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