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