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