]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
Worker: The retrial value can now skip retrial levels
[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 `next_try` > ?", DateTimeFormat::utcNow()]);
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                                 $entries = $deferred + $waiting_processes;
690                         } else {
691                                 $entries = self::totalEntries();
692                                 $waiting_processes = max(0, $entries - $deferred);
693                                 $stamp = (float)microtime(true);
694                                 $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`");
695                                 self::$db_duration += (microtime(true) - $stamp);
696                                 self::$db_duration_stat += (microtime(true) - $stamp);
697
698                                 while ($entry = DBA::fetch($jobs)) {
699                                         $idle_workers -= $entry["running"];
700                                         $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
701                                 }
702                                 DBA::close($jobs);
703                         }
704
705                         $listitem[0] = "0:" . max(0, $idle_workers);
706
707                         $processlist .= ' ('.implode(', ', $listitem).')';
708
709                         if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
710                                 $top_priority = self::highestPriority();
711                                 $high_running = self::processWithPriorityActive($top_priority);
712
713                                 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
714                                         Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
715                                         $queues = $active + 1;
716                                 }
717                         }
718
719                         Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
720
721                         // Are there fewer workers running as possible? Then fork a new one.
722                         if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
723                                 Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
724                                 if (Config::get('system', 'worker_daemon_mode', false)) {
725                                         self::IPCSetJobState(true);
726                                 } else {
727                                         self::spawnWorker();
728                                 }
729                         }
730                 }
731
732                 // if there are too much worker, we don't spawn a new one.
733                 if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
734                         self::IPCSetJobState(false);
735                 }
736
737                 return $active > $queues;
738         }
739
740         /**
741          * @brief Returns the number of active worker processes
742          *
743          * @return integer Number of active worker processes
744          * @throws \Exception
745          */
746         private static function activeWorkers()
747         {
748                 $stamp = (float)microtime(true);
749                 $count = DBA::count('process', ['command' => 'Worker.php']);
750                 self::$db_duration += (microtime(true) - $stamp);
751                 return $count;
752         }
753
754         /**
755          * @brief Returns waiting jobs for the current process id
756          *
757          * @return array waiting workerqueue jobs
758          * @throws \Exception
759          */
760         private static function getWaitingJobForPID()
761         {
762                 $stamp = (float)microtime(true);
763                 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
764                 self::$db_duration += (microtime(true) - $stamp);
765                 if (DBA::isResult($r)) {
766                         return DBA::toArray($r);
767                 }
768                 DBA::close($r);
769
770                 return false;
771         }
772
773         /**
774          * @brief Returns the next jobs that should be executed
775          *
776          * @return array array with next jobs
777          * @throws \Exception
778          */
779         private static function nextProcess()
780         {
781                 $priority = self::nextPriority();
782                 if (empty($priority)) {
783                         Logger::info('No tasks found');
784                         return [];
785                 }
786
787                 $limit = Config::get('system', 'worker_fetch_limit', 1);
788
789                 $ids = [];
790                 $stamp = (float)microtime(true);
791                 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
792                 $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['created']]);
793                 self::$db_duration += (microtime(true) - $stamp);
794                 while ($task = DBA::fetch($tasks)) {
795                         $ids[] = $task['id'];
796                         // Only continue that loop while we are storing commands that can be processed quickly
797                         $command = json_decode($task['parameter'])[0];
798                         if (!in_array($command, self::FAST_COMMANDS)) {
799                                 break;
800                         }
801                 }
802                 DBA::close($tasks);
803
804                 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
805                 return $ids;
806         }
807
808         /**
809          * @brief Returns the priority of the next workerqueue job
810          *
811          * @return string priority
812          * @throws \Exception
813          */
814         private static function nextPriority()
815         {
816                 $waiting = [];
817                 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
818                 foreach ($priorities as $priority) {
819                         $stamp = (float)microtime(true);
820                         if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
821                                 $waiting[$priority] = true;
822                         }
823                         self::$db_duration += (microtime(true) - $stamp);
824                 }
825
826                 if (!empty($waiting[PRIORITY_CRITICAL])) {
827                         return PRIORITY_CRITICAL;
828                 }
829
830                 $running = [];
831                 $running_total = 0;
832                 $stamp = (float)microtime(true);
833                 $processes = DBA::p("SELECT COUNT(DISTINCT(`process`.`pid`)) AS `running`, `priority` FROM `process`
834                         INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`
835                         WHERE NOT `done` GROUP BY `priority`");
836                 self::$db_duration += (microtime(true) - $stamp);
837                 while ($process = DBA::fetch($processes)) {
838                         $running[$process['priority']] = $process['running'];
839                         $running_total += $process['running'];
840                 }
841                 DBA::close($processes);
842
843                 foreach ($priorities as $priority) {
844                         if (!empty($waiting[$priority]) && empty($running[$priority])) {
845                                 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
846                                 return $priority;
847                         }
848                 }
849
850                 $active = max(self::activeWorkers(), $running_total);
851                 $priorities = max(count($waiting), count($running));
852                 $exponent = 2;
853
854                 $total = 0;
855                 for ($i = 1; $i <= $priorities; ++$i) {
856                         $total += pow($i, $exponent);
857                 }
858
859                 $limit = [];
860                 for ($i = 1; $i <= $priorities; ++$i) {
861                         $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
862                 }
863
864                 $i = 0;
865                 foreach ($running as $priority => $workers) {
866                         if ($workers < $limit[$i++]) {
867                                 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
868                                 return $priority;
869                         }
870                 }
871
872                 if (!empty($waiting)) {
873                         $priority = array_keys($waiting)[0];
874                         Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
875                         return $priority;
876                 }
877
878                 return false;
879         }
880
881         /**
882          * @brief Find and claim the next worker process for us
883          *
884          * @return boolean Have we found something?
885          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
886          */
887         private static function findWorkerProcesses()
888         {
889                 $mypid = getmypid();
890
891                 $ids = self::nextProcess();
892
893                 // If there is no result we check without priority limit
894                 if (empty($ids)) {
895                         $limit = Config::get('system', 'worker_fetch_limit', 1);
896
897                         $stamp = (float)microtime(true);
898                         $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
899                         $tasks = DBA::select('workerqueue', ['id', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'created']]);
900                         self::$db_duration += (microtime(true) - $stamp);
901
902                         while ($task = DBA::fetch($tasks)) {
903                                 $ids[] = $task['id'];
904                                 // Only continue that loop while we are storing commands that can be processed quickly
905                                 $command = json_decode($task['parameter'])[0];
906                                 if (!in_array($command, self::FAST_COMMANDS)) {
907                                         break;
908                                 }
909                         }
910                         DBA::close($tasks);
911                 }
912
913                 if (!empty($ids)) {
914                         $stamp = (float)microtime(true);
915                         $condition = ['id' => $ids, 'done' => false, 'pid' => 0];
916                         DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $condition);
917                         self::$db_duration += (microtime(true) - $stamp);
918                         self::$db_duration_write += (microtime(true) - $stamp);
919                 }
920
921                 return !empty($ids);
922         }
923
924         /**
925          * @brief Returns the next worker process
926          *
927          * @return string SQL statement
928          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929          */
930         public static function workerProcess()
931         {
932                 // There can already be jobs for us in the queue.
933                 $waiting = self::getWaitingJobForPID();
934                 if (!empty($waiting)) {
935                         return $waiting;
936                 }
937
938                 $stamp = (float)microtime(true);
939                 if (!Lock::acquire('worker_process')) {
940                         return false;
941                 }
942                 self::$lock_duration += (microtime(true) - $stamp);
943
944                 $found = self::findWorkerProcesses();
945
946                 Lock::release('worker_process');
947
948                 if ($found) {
949                         $stamp = (float)microtime(true);
950                         $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
951                         self::$db_duration += (microtime(true) - $stamp);
952                         return DBA::toArray($r);
953                 }
954                 return false;
955         }
956
957         /**
958          * @brief Removes a workerqueue entry from the current process
959          * @return void
960          * @throws \Exception
961          */
962         public static function unclaimProcess()
963         {
964                 $mypid = getmypid();
965
966                 $stamp = (float)microtime(true);
967                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
968                 self::$db_duration += (microtime(true) - $stamp);
969                 self::$db_duration_write += (microtime(true) - $stamp);
970         }
971
972         /**
973          * @brief Call the front end worker
974          * @return void
975          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
976          */
977         public static function callWorker()
978         {
979                 if (!Config::get("system", "frontend_worker")) {
980                         return;
981                 }
982
983                 $url = System::baseUrl()."/worker";
984                 Network::fetchUrl($url, false, 1);
985         }
986
987         /**
988          * @brief Call the front end worker if there aren't any active
989          * @return void
990          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991          */
992         public static function executeIfIdle()
993         {
994                 if (!Config::get("system", "frontend_worker")) {
995                         return;
996                 }
997
998                 // Do we have "proc_open"? Then we can fork the worker
999                 if (function_exists("proc_open")) {
1000                         // When was the last time that we called the worker?
1001                         // Less than one minute? Then we quit
1002                         if ((time() - Config::get("system", "worker_started")) < 60) {
1003                                 return;
1004                         }
1005
1006                         Config::set("system", "worker_started", time());
1007
1008                         // Do we have enough running workers? Then we quit here.
1009                         if (self::tooMuchWorkers()) {
1010                                 // Cleaning dead processes
1011                                 self::killStaleWorkers();
1012                                 Process::deleteInactive();
1013
1014                                 return;
1015                         }
1016
1017                         self::runCron();
1018
1019                         Logger::log('Call worker', Logger::DEBUG);
1020                         self::spawnWorker();
1021                         return;
1022                 }
1023
1024                 // We cannot execute background processes.
1025                 // We now run the processes from the frontend.
1026                 // This won't work with long running processes.
1027                 self::runCron();
1028
1029                 self::clearProcesses();
1030
1031                 $workers = self::activeWorkers();
1032
1033                 if ($workers == 0) {
1034                         self::callWorker();
1035                 }
1036         }
1037
1038         /**
1039          * @brief Removes long running worker processes
1040          * @return void
1041          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1042          */
1043         public static function clearProcesses()
1044         {
1045                 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1046
1047                 /// @todo We should clean up the corresponding workerqueue entries as well
1048                 $stamp = (float)microtime(true);
1049                 $condition = ["`created` < ? AND `command` = 'worker.php'",
1050                                 DateTimeFormat::utc("now - ".$timeout." minutes")];
1051                 DBA::delete('process', $condition);
1052                 self::$db_duration = (microtime(true) - $stamp);
1053                 self::$db_duration_write += (microtime(true) - $stamp);
1054         }
1055
1056         /**
1057          * @brief Runs the cron processes
1058          * @return void
1059          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1060          */
1061         private static function runCron()
1062         {
1063                 Logger::log('Add cron entries', Logger::DEBUG);
1064
1065                 // Check for spooled items
1066                 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1067
1068                 // Run the cron job that calls all other jobs
1069                 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1070
1071                 // Cleaning dead processes
1072                 self::killStaleWorkers();
1073         }
1074
1075         /**
1076          * @brief Spawns a new worker
1077          * @param bool $do_cron
1078          * @return void
1079          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080          */
1081         public static function spawnWorker($do_cron = false)
1082         {
1083                 $command = 'bin/worker.php';
1084
1085                 $args = ['no_cron' => !$do_cron];
1086
1087                 get_app()->proc_run($command, $args);
1088
1089                 // after spawning we have to remove the flag.
1090                 if (Config::get('system', 'worker_daemon_mode', false)) {
1091                         self::IPCSetJobState(false);
1092                 }
1093         }
1094
1095         /**
1096          * @brief Adds tasks to the worker queue
1097          *
1098          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1099          *
1100          * next args are passed as $cmd command line
1101          * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1102          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1103          *
1104          * @return boolean "false" if proc_run couldn't be executed
1105          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1106          * @note $cmd and string args are surrounded with ""
1107          *
1108          * @hooks 'proc_run'
1109          *    array $arr
1110          *
1111          */
1112         public static function add($cmd)
1113         {
1114                 $args = func_get_args();
1115
1116                 if (!count($args)) {
1117                         return false;
1118                 }
1119
1120                 $arr = ['args' => $args, 'run_cmd' => true];
1121
1122                 Hook::callAll("proc_run", $arr);
1123                 if (!$arr['run_cmd'] || !count($args)) {
1124                         return true;
1125                 }
1126
1127                 $priority = PRIORITY_MEDIUM;
1128                 // Don't fork from frontend tasks by default
1129                 $dont_fork = Config::get("system", "worker_dont_fork", false) || !\get_app()->isBackend();
1130                 $created = DateTimeFormat::utcNow();
1131                 $force_priority = false;
1132
1133                 $run_parameter = array_shift($args);
1134
1135                 if (is_int($run_parameter)) {
1136                         $priority = $run_parameter;
1137                 } elseif (is_array($run_parameter)) {
1138                         if (isset($run_parameter['priority'])) {
1139                                 $priority = $run_parameter['priority'];
1140                         }
1141                         if (isset($run_parameter['created'])) {
1142                                 $created = $run_parameter['created'];
1143                         }
1144                         if (isset($run_parameter['dont_fork'])) {
1145                                 $dont_fork = $run_parameter['dont_fork'];
1146                         }
1147                         if (isset($run_parameter['force_priority'])) {
1148                                 $force_priority = $run_parameter['force_priority'];
1149                         }
1150                 }
1151
1152                 $parameters = json_encode($args);
1153                 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1154
1155                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1156                 if (DBA::errorNo() != 0) {
1157                         return false;
1158                 }
1159
1160                 if (!$found) {
1161                         DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1162                 } elseif ($force_priority) {
1163                         DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1164                 }
1165
1166                 // Should we quit and wait for the worker to be called as a cronjob?
1167                 if ($dont_fork) {
1168                         return true;
1169                 }
1170
1171                 // If there is a lock then we don't have to check for too much worker
1172                 if (!Lock::acquire('worker', 0)) {
1173                         return true;
1174                 }
1175
1176                 // If there are already enough workers running, don't fork another one
1177                 $quit = self::tooMuchWorkers();
1178                 Lock::release('worker');
1179
1180                 if ($quit) {
1181                         return true;
1182                 }
1183
1184                 // We tell the daemon that a new job entry exists
1185                 if (Config::get('system', 'worker_daemon_mode', false)) {
1186                         // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1187                         return true;
1188                 }
1189
1190                 // Now call the worker to execute the jobs that we just added to the queue
1191                 self::spawnWorker();
1192
1193                 return true;
1194         }
1195
1196         /**
1197          * Returns the next retrial level for worker jobs.
1198          * This function will skip levels when jobs are older.
1199          *
1200          * @param array $queue Worker queue entry
1201          * @param integer $max_level maximum retrial level
1202          * @return integer the next retrial level value
1203          */
1204         private static function getNextRetrial($queue, $max_level)
1205         {
1206                 $created = strtotime($queue['created']);
1207                 $retrial_time = time() - $created;
1208
1209                 $new_retrial = $queue['retrial'] + 1;
1210                 $total = 0;
1211                 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1212                         $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1213                         $total += $delay;
1214                         if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1215                                 $new_retrial = $retrial;
1216                         }
1217                 }
1218                 Logger::info('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1219                 return $new_retrial;
1220         }
1221
1222         /**
1223          * Defers the current worker entry
1224          */
1225         public static function defer()
1226         {
1227                 if (empty(BaseObject::getApp()->queue)) {
1228                         return;
1229                 }
1230
1231                 $queue = BaseObject::getApp()->queue;
1232
1233                 $retrial = $queue['retrial'];
1234                 $id = $queue['id'];
1235                 $priority = $queue['priority'];
1236
1237                 $max_level = 15;
1238                 $new_retrial = self::getNextRetrial($queue, $max_level);
1239
1240                 if ($new_retrial > $max_level) {
1241                         Logger::info('The task exceeded the maximum retry count', ['id' => $id, 'max_level' => $max_level, 'retrial' => $new_retrial]);
1242                         return;
1243                 }
1244
1245                 // Calculate the delay until the next trial
1246                 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1247                 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1248
1249                 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1250                         $priority = PRIORITY_MEDIUM;
1251                 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1252                         $priority = PRIORITY_LOW;
1253                 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1254                         $priority = PRIORITY_NEGLIGIBLE;
1255                 }
1256
1257                 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1258
1259                 $stamp = (float)microtime(true);
1260                 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1261                 DBA::update('workerqueue', $fields, ['id' => $id]);
1262                 self::$db_duration += (microtime(true) - $stamp);
1263                 self::$db_duration_write += (microtime(true) - $stamp);
1264         }
1265
1266         /**
1267          * Log active processes into the "process" table
1268          *
1269          * @brief Log active processes into the "process" table
1270          */
1271         public static function startProcess()
1272         {
1273                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1274
1275                 $command = basename($trace[0]['file']);
1276
1277                 Process::deleteInactive();
1278
1279                 Process::insert($command);
1280         }
1281
1282         /**
1283          * Remove the active process from the "process" table
1284          *
1285          * @brief Remove the active process from the "process" table
1286          * @return bool
1287          * @throws \Exception
1288          */
1289         public static function endProcess()
1290         {
1291                 return Process::deleteByPid();
1292         }
1293
1294         /**
1295          * Set the flag if some job is waiting
1296          *
1297          * @brief Set the flag if some job is waiting
1298          * @param boolean $jobs Is there a waiting job?
1299          * @throws \Exception
1300          */
1301         public static function IPCSetJobState($jobs)
1302         {
1303                 $stamp = (float)microtime(true);
1304                 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1305                 self::$db_duration += (microtime(true) - $stamp);
1306                 self::$db_duration_write += (microtime(true) - $stamp);
1307         }
1308
1309         /**
1310          * Checks if some worker job waits to be executed
1311          *
1312          * @brief Checks if some worker job waits to be executed
1313          * @return bool
1314          * @throws \Exception
1315          */
1316         public static function IPCJobsExists()
1317         {
1318                 $stamp = (float)microtime(true);
1319                 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1320                 self::$db_duration += (microtime(true) - $stamp);
1321
1322                 // When we don't have a row, no job is running
1323                 if (!DBA::isResult($row)) {
1324                         return false;
1325                 }
1326
1327                 return (bool)$row['jobs'];
1328         }
1329 }