]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
afc8b5ab3a7a16c074a2c92b7d2db55124605a82
[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                 Logger::log(
415                         'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
416                         ' - DB-Count: '.number_format(self::$db_duration_count, 4).
417                         ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
418                         ' - DB-Write: '.number_format(self::$db_duration_write, 4).
419                         ' - Lock: '.number_format(self::$lock_duration, 4).
420                         ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
421                         ' - Execution: '.number_format($duration, 4),
422                         Logger::DEBUG
423                 );
424
425                 self::$up_start = microtime(true);
426                 self::$db_duration = 0;
427                 self::$db_duration_count = 0;
428                 self::$db_duration_stat = 0;
429                 self::$db_duration_write = 0;
430                 self::$lock_duration = 0;
431
432                 if ($duration > 3600) {
433                         Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
434                 } elseif ($duration > 600) {
435                         Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
436                 } elseif ($duration > 300) {
437                         Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
438                 } elseif ($duration > 120) {
439                         Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
440                 }
441
442                 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".number_format($duration, 4)." seconds. Process PID: ".$new_process_id);
443
444                 // Write down the performance values into the log
445                 if (Config::get("system", "profiler")) {
446                         $duration = microtime(true)-$a->performance["start"];
447
448                         $o = '';
449                         if (Config::get("rendertime", "callstack")) {
450                                 if (isset($a->callstack["database"])) {
451                                         $o .= "\nDatabase Read:\n";
452                                         foreach ($a->callstack["database"] as $func => $time) {
453                                                 $time = round($time, 3);
454                                                 if ($time > 0) {
455                                                         $o .= $func.": ".$time."\n";
456                                                 }
457                                         }
458                                 }
459                                 if (isset($a->callstack["database_write"])) {
460                                         $o .= "\nDatabase Write:\n";
461                                         foreach ($a->callstack["database_write"] as $func => $time) {
462                                                 $time = round($time, 3);
463                                                 if ($time > 0) {
464                                                         $o .= $func.": ".$time."\n";
465                                                 }
466                                         }
467                                 }
468                                 if (isset($a->callstack["dache"])) {
469                                         $o .= "\nCache Read:\n";
470                                         foreach ($a->callstack["dache"] as $func => $time) {
471                                                 $time = round($time, 3);
472                                                 if ($time > 0) {
473                                                         $o .= $func.": ".$time."\n";
474                                                 }
475                                         }
476                                 }
477                                 if (isset($a->callstack["dache_write"])) {
478                                         $o .= "\nCache Write:\n";
479                                         foreach ($a->callstack["dache_write"] as $func => $time) {
480                                                 $time = round($time, 3);
481                                                 if ($time > 0) {
482                                                         $o .= $func.": ".$time."\n";
483                                                 }
484                                         }
485                                 }
486                                 if (isset($a->callstack["network"])) {
487                                         $o .= "\nNetwork:\n";
488                                         foreach ($a->callstack["network"] as $func => $time) {
489                                                 $time = round($time, 3);
490                                                 if ($time > 0) {
491                                                         $o .= $func.": ".$time."\n";
492                                                 }
493                                         }
494                                 }
495                         }
496
497                         Logger::log(
498                                 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
499                                         "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
500                                         number_format($a->performance["database"] - $a->performance["database_write"], 2),
501                                         number_format($a->performance["database_write"], 2),
502                                         number_format($a->performance["cache"], 2),
503                                         number_format($a->performance["cache_write"], 2),
504                                         number_format($a->performance["network"], 2),
505                                         number_format($a->performance["file"], 2),
506                                         number_format($duration - ($a->performance["database"]
507                                                 + $a->performance["cache"] + $a->performance["cache_write"]
508                                                 + $a->performance["network"] + $a->performance["file"]), 2),
509                                         number_format($duration, 2)
510                                 ),
511                                 Logger::DEBUG
512                         );
513                 }
514
515                 $cooldown = Config::get("system", "worker_cooldown", 0);
516
517                 if ($cooldown > 0) {
518                         Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
519                         sleep($cooldown);
520                 }
521         }
522
523         /**
524          * @brief Checks if the number of database connections has reached a critical limit.
525          *
526          * @return bool Are more than 3/4 of the maximum connections used?
527          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
528          */
529         private static function maxConnectionsReached()
530         {
531                 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
532                 $max = Config::get("system", "max_connections");
533
534                 // Fetch the percentage level where the worker will get active
535                 $maxlevel = Config::get("system", "max_connections_level", 75);
536
537                 if ($max == 0) {
538                         // the maximum number of possible user connections can be a system variable
539                         $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
540                         if (DBA::isResult($r)) {
541                                 $max = $r["Value"];
542                         }
543                         // Or it can be granted. This overrides the system variable
544                         $stamp = (float)microtime(true);
545                         $r = DBA::p('SHOW GRANTS');
546                         self::$db_duration += (microtime(true) - $stamp);
547                         while ($grants = DBA::fetch($r)) {
548                                 $grant = array_pop($grants);
549                                 if (stristr($grant, "GRANT USAGE ON")) {
550                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
551                                                 $max = $match[1];
552                                         }
553                                 }
554                         }
555                         DBA::close($r);
556                 }
557
558                 // If $max is set we will use the processlist to determine the current number of connections
559                 // The processlist only shows entries of the current user
560                 if ($max != 0) {
561                         $stamp = (float)microtime(true);
562                         $r = DBA::p('SHOW PROCESSLIST');
563                         self::$db_duration += (microtime(true) - $stamp);
564                         $used = DBA::numRows($r);
565                         DBA::close($r);
566
567                         Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
568
569                         $level = ($used / $max) * 100;
570
571                         if ($level >= $maxlevel) {
572                                 Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
573                                 return true;
574                         }
575                 }
576
577                 // We will now check for the system values.
578                 // This limit could be reached although the user limits are fine.
579                 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
580                 if (!DBA::isResult($r)) {
581                         return false;
582                 }
583                 $max = intval($r["Value"]);
584                 if ($max == 0) {
585                         return false;
586                 }
587                 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
588                 if (!DBA::isResult($r)) {
589                         return false;
590                 }
591                 $used = intval($r["Value"]);
592                 if ($used == 0) {
593                         return false;
594                 }
595                 Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
596
597                 $level = $used / $max * 100;
598
599                 if ($level < $maxlevel) {
600                         return false;
601                 }
602                 Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
603                 return true;
604         }
605
606         /**
607          * @brief fix the queue entry if the worker process died
608          * @return void
609          * @throws \Exception
610          */
611         private static function killStaleWorkers()
612         {
613                 $stamp = (float)microtime(true);
614                 $entries = DBA::select(
615                         'workerqueue',
616                         ['id', 'pid', 'executed', 'priority', 'parameter'],
617                         ['NOT `done` AND `pid` != 0'],
618                         ['order' => ['priority', 'created']]
619                 );
620                 self::$db_duration += (microtime(true) - $stamp);
621
622                 while ($entry = DBA::fetch($entries)) {
623                         if (!posix_kill($entry["pid"], 0)) {
624                                 $stamp = (float)microtime(true);
625                                 DBA::update(
626                                         'workerqueue',
627                                         ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
628                                         ['id' => $entry["id"]]
629                                 );
630                                 self::$db_duration += (microtime(true) - $stamp);
631                                 self::$db_duration_write += (microtime(true) - $stamp);
632                         } else {
633                                 // Kill long running processes
634                                 // Check if the priority is in a valid range
635                                 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
636                                         $entry["priority"] = PRIORITY_MEDIUM;
637                                 }
638
639                                 // Define the maximum durations
640                                 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
641                                 $max_duration = $max_duration_defaults[$entry["priority"]];
642
643                                 $argv = json_decode($entry["parameter"], true);
644                                 $argv[0] = basename($argv[0]);
645
646                                 // How long is the process already running?
647                                 $duration = (time() - strtotime($entry["executed"])) / 60;
648                                 if ($duration > $max_duration) {
649                                         Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
650                                         posix_kill($entry["pid"], SIGTERM);
651
652                                         // We killed the stale process.
653                                         // To avoid a blocking situation we reschedule the process at the beginning of the queue.
654                                         // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
655                                         $new_priority = $entry["priority"];
656                                         if ($entry["priority"] == PRIORITY_HIGH) {
657                                                 $new_priority = PRIORITY_MEDIUM;
658                                         } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
659                                                 $new_priority = PRIORITY_LOW;
660                                         } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
661                                                 $new_priority = PRIORITY_NEGLIGIBLE;
662                                         }
663                                         $stamp = (float)microtime(true);
664                                         DBA::update(
665                                                 'workerqueue',
666                                                 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
667                                                 ['id' => $entry["id"]]
668                                         );
669                                         self::$db_duration += (microtime(true) - $stamp);
670                                         self::$db_duration_write += (microtime(true) - $stamp);
671                                 } else {
672                                         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);
673                                 }
674                         }
675                 }
676         }
677
678         /**
679          * @brief Checks if the number of active workers exceeds the given limits
680          *
681          * @return bool Are there too much workers running?
682          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683          */
684         private static function tooMuchWorkers()
685         {
686                 $queues = Config::get("system", "worker_queues", 4);
687
688                 $maxqueues = $queues;
689
690                 $active = self::activeWorkers();
691
692                 // Decrease the number of workers at higher load
693                 $load = System::currentLoad();
694                 if ($load) {
695                         $maxsysload = intval(Config::get("system", "maxloadavg", 50));
696
697                         /* Default exponent 3 causes queues to rapidly decrease as load increases.
698                          * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
699                          * For some environments, this rapid decrease is not needed.
700                          * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
701                          */
702                         $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
703                         $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
704                         $queues = intval(ceil($slope * $maxqueues));
705
706                         $processlist = '';
707
708                         if (Config::get('system', 'worker_jpm')) {
709                                 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
710                                 $jobs_per_minute = [];
711                                 foreach ($intervals as $interval) {
712                                         if ($interval == 0) {
713                                                 continue;
714                                         } else {
715                                                 $interval = (int)$interval;
716                                         }
717
718                                         $stamp = (float)microtime(true);
719                                         $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
720                                         self::$db_duration += (microtime(true) - $stamp);
721                                         self::$db_duration_stat += (microtime(true) - $stamp);
722                                         if ($job = DBA::fetch($jobs)) {
723                                                 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
724                                         }
725                                         DBA::close($jobs);
726                                 }
727                                 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
728                         }
729
730                         // Create a list of queue entries grouped by their priority
731                         $listitem = [0 => ''];
732
733                         $idle_workers = $active;
734
735                         $deferred = self::deferredEntries();
736
737                         if (Config::get('system', 'worker_debug')) {
738                                 $waiting_processes = 0;
739                                 // Now adding all processes with workerqueue entries
740                                 $stamp = (float)microtime(true);
741                                 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` AND `next_try` < ? GROUP BY `priority`", DateTimeFormat::utcNow());
742                                 self::$db_duration += (microtime(true) - $stamp);
743                                 self::$db_duration_stat += (microtime(true) - $stamp);
744                                 while ($entry = DBA::fetch($jobs)) {
745                                         $stamp = (float)microtime(true);
746                                         $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE NOT `done` AND `priority` = ?", $entry["priority"]);
747                                         self::$db_duration += (microtime(true) - $stamp);
748                                         self::$db_duration_stat += (microtime(true) - $stamp);
749                                         if ($process = DBA::fetch($processes)) {
750                                                 $idle_workers -= $process["running"];
751                                                 $waiting_processes += $entry["entries"];
752                                                 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
753                                         }
754                                         DBA::close($processes);
755                                 }
756                                 DBA::close($jobs);
757                                 $entries = $deferred + $waiting_processes;
758                         } else {
759                                 $entries = self::totalEntries();
760                                 $waiting_processes = max(0, $entries - $deferred);
761                                 $stamp = (float)microtime(true);
762                                 $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`");
763                                 self::$db_duration += (microtime(true) - $stamp);
764                                 self::$db_duration_stat += (microtime(true) - $stamp);
765
766                                 while ($entry = DBA::fetch($jobs)) {
767                                         $idle_workers -= $entry["running"];
768                                         $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
769                                 }
770                                 DBA::close($jobs);
771                         }
772
773                         $listitem[0] = "0:" . max(0, $idle_workers);
774
775                         $processlist .= ' ('.implode(', ', $listitem).')';
776
777                         if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && self::entriesExists() && ($active >= $queues)) {
778                                 $top_priority = self::highestPriority();
779                                 $high_running = self::processWithPriorityActive($top_priority);
780
781                                 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
782                                         Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
783                                         $queues = $active + 1;
784                                 }
785                         }
786
787                         Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
788
789                         // Are there fewer workers running as possible? Then fork a new one.
790                         if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
791                                 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
792                                 if (Config::get('system', 'worker_daemon_mode', false)) {
793                                         self::IPCSetJobState(true);
794                                 } else {
795                                         self::spawnWorker();
796                                 }
797                         }
798                 }
799
800                 // if there are too much worker, we don't spawn a new one.
801                 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
802                         self::IPCSetJobState(false);
803                 }
804
805                 return $active > $queues;
806         }
807
808         /**
809          * @brief Returns the number of active worker processes
810          *
811          * @return integer Number of active worker processes
812          * @throws \Exception
813          */
814         private static function activeWorkers()
815         {
816                 $stamp = (float)microtime(true);
817                 $count = DBA::count('process', ['command' => 'Worker.php']);
818                 self::$db_duration += (microtime(true) - $stamp);
819                 return $count;
820         }
821
822         /**
823          * @brief Returns waiting jobs for the current process id
824          *
825          * @return array waiting workerqueue jobs
826          * @throws \Exception
827          */
828         private static function getWaitingJobForPID()
829         {
830                 $stamp = (float)microtime(true);
831                 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
832                 self::$db_duration += (microtime(true) - $stamp);
833                 if (DBA::isResult($r)) {
834                         return DBA::toArray($r);
835                 }
836                 DBA::close($r);
837
838                 return false;
839         }
840
841         /**
842          * @brief Returns the next jobs that should be executed
843          *
844          * @return array array with next jobs
845          * @throws \Exception
846          */
847         private static function nextProcess()
848         {
849                 $priority = self::nextPriority();
850                 if (empty($priority)) {
851                         Logger::log('No tasks found', Logger::DEBUG);
852                         return [];
853                 }
854
855                 if ($priority <= PRIORITY_MEDIUM) {
856                         $limit = Config::get('system', 'worker_fetch_limit', 1);
857                 } else {
858                         $limit = 1;
859                 }
860
861                 $ids = [];
862                 $stamp = (float)microtime(true);
863                 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
864                 $tasks = DBA::select('workerqueue', ['id'], $condition, ['limit' => $limit, 'order' => ['created']]);
865                 self::$db_duration += (microtime(true) - $stamp);
866                 while ($task = DBA::fetch($tasks)) {
867                         $ids[] = $task['id'];
868                 }
869                 DBA::close($tasks);
870
871                 Logger::log('Found task(s) ' . implode(', ', $ids) . ' with priority ' .$priority, Logger::DEBUG);
872                 return $ids;
873         }
874
875         /**
876          * @brief Returns the priority of the next workerqueue job
877          *
878          * @return string priority
879          * @throws \Exception
880          */
881         private static function nextPriority()
882         {
883                 $waiting = [];
884                 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
885                 foreach ($priorities as $priority) {
886                         $stamp = (float)microtime(true);
887                         if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
888                                 $waiting[$priority] = true;
889                         }
890                         self::$db_duration += (microtime(true) - $stamp);
891                 }
892
893                 if (!empty($waiting[PRIORITY_CRITICAL])) {
894                         return PRIORITY_CRITICAL;
895                 }
896
897                 $running = [];
898                 $running_total = 0;
899                 $stamp = (float)microtime(true);
900                 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
901                         INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
902                         WHERE NOT `done` GROUP BY `priority`");
903                 self::$db_duration += (microtime(true) - $stamp);
904                 while ($process = DBA::fetch($processes)) {
905                         $running[$process['priority']] = $process['running'];
906                         $running_total += $process['running'];
907                 }
908                 DBA::close($processes);
909
910                 foreach ($priorities as $priority) {
911                         if (!empty($waiting[$priority]) && empty($running[$priority])) {
912                                 Logger::log('No running worker found with priority ' . $priority . ' - assigning it.', Logger::DEBUG);
913                                 return $priority;
914                         }
915                 }
916
917                 $active = max(self::activeWorkers(), $running_total);
918                 $priorities = max(count($waiting), count($running));
919                 $exponent = 2;
920
921                 $total = 0;
922                 for ($i = 1; $i <= $priorities; ++$i) {
923                         $total += pow($i, $exponent);
924                 }
925
926                 $limit = [];
927                 for ($i = 1; $i <= $priorities; ++$i) {
928                         $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
929                 }
930
931                 $i = 0;
932                 foreach ($running as $priority => $workers) {
933                         if ($workers < $limit[$i++]) {
934                                 Logger::log('Priority ' . $priority . ' has got ' . $workers . ' workers out of a limit of ' . $limit[$i - 1], Logger::DEBUG);
935                                 return $priority;
936                         }
937                 }
938
939                 if (!empty($waiting)) {
940                         $priority =  array_shift(array_keys($waiting));
941                         Logger::log('No underassigned priority found, now taking the highest priority (' . $priority . ').', Logger::DEBUG);
942                         return $priority;
943                 }
944
945                 return false;
946         }
947
948         /**
949          * @brief Find and claim the next worker process for us
950          *
951          * @return boolean Have we found something?
952          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953          */
954         private static function findWorkerProcesses()
955         {
956                 $mypid = getmypid();
957
958                 $ids = self::nextProcess();
959
960                 // If there is no result we check without priority limit
961                 if (empty($ids)) {
962                         $stamp = (float)microtime(true);
963                         $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
964                         $result = DBA::select('workerqueue', ['id'], $condition, ['limit' => 1, 'order' => ['priority', 'created']]);
965                         self::$db_duration += (microtime(true) - $stamp);
966
967                         while ($id = DBA::fetch($result)) {
968                                 $ids[] = $id["id"];
969                         }
970                         DBA::close($result);
971                 }
972
973                 if (!empty($ids)) {
974                         $stamp = (float)microtime(true);
975                         $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
976                         DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
977                         self::$db_duration += (microtime(true) - $stamp);
978                         self::$db_duration_write += (microtime(true) - $stamp);
979                 }
980
981                 return !empty($ids);
982         }
983
984         /**
985          * @brief Returns the next worker process
986          *
987          * @return string SQL statement
988          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989          */
990         public static function workerProcess()
991         {
992                 // There can already be jobs for us in the queue.
993                 $waiting = self::getWaitingJobForPID();
994                 if (!empty($waiting)) {
995                         return $waiting;
996                 }
997
998                 $stamp = (float)microtime(true);
999                 if (!Lock::acquire('worker_process')) {
1000                         return false;
1001                 }
1002                 self::$lock_duration += (microtime(true) - $stamp);
1003
1004                 $found = self::findWorkerProcesses();
1005
1006                 Lock::release('worker_process');
1007
1008                 if ($found) {
1009                         $stamp = (float)microtime(true);
1010                         $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1011                         self::$db_duration += (microtime(true) - $stamp);
1012                         return DBA::toArray($r);
1013                 }
1014                 return false;
1015         }
1016
1017         /**
1018          * @brief Removes a workerqueue entry from the current process
1019          * @return void
1020          * @throws \Exception
1021          */
1022         public static function unclaimProcess()
1023         {
1024                 $mypid = getmypid();
1025
1026                 $stamp = (float)microtime(true);
1027                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1028                 self::$db_duration += (microtime(true) - $stamp);
1029                 self::$db_duration_write += (microtime(true) - $stamp);
1030         }
1031
1032         /**
1033          * @brief Call the front end worker
1034          * @return void
1035          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1036          */
1037         public static function callWorker()
1038         {
1039                 if (!Config::get("system", "frontend_worker")) {
1040                         return;
1041                 }
1042
1043                 $url = System::baseUrl()."/worker";
1044                 Network::fetchUrl($url, false, $redirects, 1);
1045         }
1046
1047         /**
1048          * @brief Call the front end worker if there aren't any active
1049          * @return void
1050          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1051          */
1052         public static function executeIfIdle()
1053         {
1054                 if (!Config::get("system", "frontend_worker")) {
1055                         return;
1056                 }
1057
1058                 // Do we have "proc_open"? Then we can fork the worker
1059                 if (function_exists("proc_open")) {
1060                         // When was the last time that we called the worker?
1061                         // Less than one minute? Then we quit
1062                         if ((time() - Config::get("system", "worker_started")) < 60) {
1063                                 return;
1064                         }
1065
1066                         Config::set("system", "worker_started", time());
1067
1068                         // Do we have enough running workers? Then we quit here.
1069                         if (self::tooMuchWorkers()) {
1070                                 // Cleaning dead processes
1071                                 self::killStaleWorkers();
1072                                 Process::deleteInactive();
1073
1074                                 return;
1075                         }
1076
1077                         self::runCron();
1078
1079                         Logger::log('Call worker', Logger::DEBUG);
1080                         self::spawnWorker();
1081                         return;
1082                 }
1083
1084                 // We cannot execute background processes.
1085                 // We now run the processes from the frontend.
1086                 // This won't work with long running processes.
1087                 self::runCron();
1088
1089                 self::clearProcesses();
1090
1091                 $workers = self::activeWorkers();
1092
1093                 if ($workers == 0) {
1094                         self::callWorker();
1095                 }
1096         }
1097
1098         /**
1099          * @brief Removes long running worker processes
1100          * @return void
1101          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1102          */
1103         public static function clearProcesses()
1104         {
1105                 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1106
1107                 /// @todo We should clean up the corresponding workerqueue entries as well
1108                 $stamp = (float)microtime(true);
1109                 $condition = ["`created` < ? AND `command` = 'worker.php'",
1110                                 DateTimeFormat::utc("now - ".$timeout." minutes")];
1111                 DBA::delete('process', $condition);
1112                 self::$db_duration = (microtime(true) - $stamp);
1113                 self::$db_duration_write += (microtime(true) - $stamp);
1114         }
1115
1116         /**
1117          * @brief Runs the cron processes
1118          * @return void
1119          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1120          */
1121         private static function runCron()
1122         {
1123                 Logger::log('Add cron entries', Logger::DEBUG);
1124
1125                 // Check for spooled items
1126                 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1127
1128                 // Run the cron job that calls all other jobs
1129                 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1130
1131                 // Cleaning dead processes
1132                 self::killStaleWorkers();
1133         }
1134
1135         /**
1136          * @brief Spawns a new worker
1137          * @param bool $do_cron
1138          * @return void
1139          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140          */
1141         public static function spawnWorker($do_cron = false)
1142         {
1143                 $command = 'bin/worker.php';
1144
1145                 $args = ['no_cron' => !$do_cron];
1146
1147                 get_app()->proc_run($command, $args);
1148
1149                 // after spawning we have to remove the flag.
1150                 if (Config::get('system', 'worker_daemon_mode', false)) {
1151                         self::IPCSetJobState(false);
1152                 }
1153         }
1154
1155         /**
1156          * @brief Adds tasks to the worker queue
1157          *
1158          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1159          *
1160          * next args are passed as $cmd command line
1161          * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1162          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1163          *
1164          * @return boolean "false" if proc_run couldn't be executed
1165          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1166          * @note $cmd and string args are surrounded with ""
1167          *
1168          * @hooks 'proc_run'
1169          *    array $arr
1170          *
1171          */
1172         public static function add($cmd)
1173         {
1174                 $args = func_get_args();
1175
1176                 if (!count($args)) {
1177                         return false;
1178                 }
1179
1180                 $arr = ['args' => $args, 'run_cmd' => true];
1181
1182                 Hook::callAll("proc_run", $arr);
1183                 if (!$arr['run_cmd'] || !count($args)) {
1184                         return true;
1185                 }
1186
1187                 $priority = PRIORITY_MEDIUM;
1188                 $dont_fork = Config::get("system", "worker_dont_fork", false);
1189                 $created = DateTimeFormat::utcNow();
1190                 $force_priority = false;
1191
1192                 $run_parameter = array_shift($args);
1193
1194                 if (is_int($run_parameter)) {
1195                         $priority = $run_parameter;
1196                 } elseif (is_array($run_parameter)) {
1197                         if (isset($run_parameter['priority'])) {
1198                                 $priority = $run_parameter['priority'];
1199                         }
1200                         if (isset($run_parameter['created'])) {
1201                                 $created = $run_parameter['created'];
1202                         }
1203                         if (isset($run_parameter['dont_fork'])) {
1204                                 $dont_fork = $run_parameter['dont_fork'];
1205                         }
1206                         if (isset($run_parameter['force_priority'])) {
1207                                 $force_priority = $run_parameter['force_priority'];
1208                         }
1209                 }
1210
1211                 $parameters = json_encode($args);
1212                 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1213
1214                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1215                 if (DBA::errorNo() != 0) {
1216                         return false;
1217                 }
1218
1219                 if (!$found) {
1220                         DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1221                 } elseif ($force_priority) {
1222                         DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1223                 }
1224
1225                 // Should we quit and wait for the worker to be called as a cronjob?
1226                 if ($dont_fork) {
1227                         return true;
1228                 }
1229
1230                 // If there is a lock then we don't have to check for too much worker
1231                 if (!Lock::acquire('worker', 0)) {
1232                         return true;
1233                 }
1234
1235                 // If there are already enough workers running, don't fork another one
1236                 $quit = self::tooMuchWorkers();
1237                 Lock::release('worker');
1238
1239                 if ($quit) {
1240                         return true;
1241                 }
1242
1243                 // We tell the daemon that a new job entry exists
1244                 if (Config::get('system', 'worker_daemon_mode', false)) {
1245                         // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1246                         return true;
1247                 }
1248
1249                 // Now call the worker to execute the jobs that we just added to the queue
1250                 self::spawnWorker();
1251
1252                 return true;
1253         }
1254
1255         /**
1256          * Defers the current worker entry
1257          */
1258         public static function defer()
1259         {
1260                 if (empty(BaseObject::getApp()->queue)) {
1261                         return;
1262                 }
1263
1264                 $queue = BaseObject::getApp()->queue;
1265
1266                 $retrial = $queue['retrial'];
1267                 $id = $queue['id'];
1268                 $priority = $queue['priority'];
1269
1270                 if ($retrial > 14) {
1271                         Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1272                         return;
1273                 }
1274
1275                 // Calculate the delay until the next trial
1276                 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1277                 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1278
1279                 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1280                         $priority = PRIORITY_MEDIUM;
1281                 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1282                         $priority = PRIORITY_LOW;
1283                 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1284                         $priority = PRIORITY_NEGLIGIBLE;
1285                 }
1286
1287                 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1288
1289                 $stamp = (float)microtime(true);
1290                 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1291                 DBA::update('workerqueue', $fields, ['id' => $id]);
1292                 self::$db_duration += (microtime(true) - $stamp);
1293                 self::$db_duration_write += (microtime(true) - $stamp);
1294         }
1295
1296         /**
1297          * Log active processes into the "process" table
1298          *
1299          * @brief Log active processes into the "process" table
1300          */
1301         public static function startProcess()
1302         {
1303                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1304
1305                 $command = basename($trace[0]['file']);
1306
1307                 Process::deleteInactive();
1308
1309                 Process::insert($command);
1310         }
1311
1312         /**
1313          * Remove the active process from the "process" table
1314          *
1315          * @brief Remove the active process from the "process" table
1316          * @return bool
1317          * @throws \Exception
1318          */
1319         public static function endProcess()
1320         {
1321                 return Process::deleteByPid();
1322         }
1323
1324         /**
1325          * Set the flag if some job is waiting
1326          *
1327          * @brief Set the flag if some job is waiting
1328          * @param boolean $jobs Is there a waiting job?
1329          * @throws \Exception
1330          */
1331         public static function IPCSetJobState($jobs)
1332         {
1333                 $stamp = (float)microtime(true);
1334                 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1335                 self::$db_duration += (microtime(true) - $stamp);
1336                 self::$db_duration_write += (microtime(true) - $stamp);
1337         }
1338
1339         /**
1340          * Checks if some worker job waits to be executed
1341          *
1342          * @brief Checks if some worker job waits to be executed
1343          * @return bool
1344          * @throws \Exception
1345          */
1346         public static function IPCJobsExists()
1347         {
1348                 $stamp = (float)microtime(true);
1349                 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1350                 self::$db_duration += (microtime(true) - $stamp);
1351
1352                 // When we don't have a row, no job is running
1353                 if (!DBA::isResult($row)) {
1354                         return false;
1355                 }
1356
1357                 return (bool)$row['jobs'];
1358         }
1359 }