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