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