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