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