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