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