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