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