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