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