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