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