]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
c8a4c038bbc44f78f5979171cee2cfc71ab3e0de
[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                 self::$up_start = microtime(true);
44
45                 // At first check the maximum load. We shouldn't continue with a high load
46                 if ($a->isMaxLoadReached()) {
47                         Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
48                         return;
49                 }
50
51                 // We now start the process. This is done after the load check since this could increase the load.
52                 self::startProcess();
53
54                 // Kill stale processes every 5 minutes
55                 $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
56                 if (time() > ($last_cleanup + 300)) {
57                         Config::set('system', 'worker_last_cleaned', time());
58                         self::killStaleWorkers();
59                 }
60
61                 // Count active workers and compare them with a maximum value that depends on the load
62                 if (self::tooMuchWorkers()) {
63                         Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
64                         return;
65                 }
66
67                 // Do we have too few memory?
68                 if ($a->isMinMemoryReached()) {
69                         Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
70                         return;
71                 }
72
73                 // Possibly there are too much database connections
74                 if (self::maxConnectionsReached()) {
75                         Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
76                         return;
77                 }
78
79                 // Possibly there are too much database processes that block the system
80                 if ($a->isMaxProcessesReached()) {
81                         Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
82                         return;
83                 }
84
85                 // Now we start additional cron processes if we should do so
86                 if ($run_cron) {
87                         self::runCron();
88                 }
89
90                 $starttime = time();
91
92                 $entries = 0;
93                 $deferred = 0;
94
95                 // We fetch the next queue entry that is about to be executed
96                 while ($r = self::workerProcess($passing_slow, $entries, $deferred)) {
97                         // When we are processing jobs with a lower priority, we don't refetch new jobs
98                         // Otherwise fast jobs could wait behind slow ones and could be blocked.
99                         $refetched = $passing_slow;
100
101                         foreach ($r as $entry) {
102                                 // Assure that the priority is an integer value
103                                 $entry['priority'] = (int)$entry['priority'];
104
105                                 // The work will be done
106                                 if (!self::execute($entry)) {
107                                         Logger::log('Process execution failed, quitting.', Logger::DEBUG);
108                                         return;
109                                 }
110
111                                 // If possible we will fetch new jobs for this worker
112                                 if (!$refetched) {
113                                         $entries = self::totalEntries();
114                                         $deferred = self::deferredEntries();
115                                         if (Lock::acquire('worker_process', 0)) {
116                                                 $refetched = self::findWorkerProcesses($passing_slow, $entries, $deferred);
117                                                 Lock::release('worker_process');
118                                         }
119                                 }
120                         }
121
122                         // To avoid the quitting of multiple workers only one worker at a time will execute the check
123                         if (Lock::acquire('worker', 0)) {
124                                 // Count active workers and compare them with a maximum value that depends on the load
125                                 if (self::tooMuchWorkers($entries, $deferred)) {
126                                         Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
127                                         Lock::release('worker');
128                                         return;
129                                 }
130
131                                 // Check free memory
132                                 if ($a->isMinMemoryReached()) {
133                                         Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
134                                         Lock::release('worker');
135                                         return;
136                                 }
137                                 Lock::release('worker');
138                         }
139
140                         // Quit the worker once every 5 minutes
141                         if (time() > ($starttime + 300)) {
142                                 Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
143                                 return;
144                         }
145                 }
146
147                 // Cleaning up. Possibly not needed, but it doesn't harm anything.
148                 if (Config::get('system', 'worker_daemon_mode', false)) {
149                         self::IPCSetJobState(false);
150                 }
151                 Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
152         }
153
154         /**
155          * @brief Check if non executed tasks do exist in the worker queue
156          *
157          * @return boolean Returns "true" if tasks are existing
158          * @throws \Exception
159          */
160         private static function entriesExists()
161         {
162                 $stamp = (float)microtime(true);
163                 $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
164                 self::$db_duration += (microtime(true) - $stamp);
165                 return $exists;
166         }
167
168         /**
169          * @brief Returns the number of deferred entries in the worker queue
170          *
171          * @return integer Number of deferred entries in the worker queue
172          * @throws \Exception
173          */
174         private static function deferredEntries()
175         {
176                 $stamp = (float)microtime(true);
177                 $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` > ?", DateTimeFormat::utcNow()]);
178                 self::$db_duration += (microtime(true) - $stamp);
179                 self::$db_duration_count += (microtime(true) - $stamp);
180                 return $count;
181         }
182
183         /**
184          * @brief Returns the number of non executed entries in the worker queue
185          *
186          * @return integer Number of non executed entries in the worker queue
187          * @throws \Exception
188          */
189         private static function totalEntries()
190         {
191                 $stamp = (float)microtime(true);
192                 $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
193                 self::$db_duration += (microtime(true) - $stamp);
194                 self::$db_duration_count += (microtime(true) - $stamp);
195                 return $count;
196         }
197
198         /**
199          * @brief Returns the highest priority in the worker queue that isn't executed
200          *
201          * @return integer Number of active worker processes
202          * @throws \Exception
203          */
204         private static function highestPriority()
205         {
206                 $stamp = (float)microtime(true);
207                 $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
208                 $workerqueue = DBA::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
209                 self::$db_duration += (microtime(true) - $stamp);
210                 if (DBA::isResult($workerqueue)) {
211                         return $workerqueue["priority"];
212                 } else {
213                         return 0;
214                 }
215         }
216
217         /**
218          * @brief Returns if a process with the given priority is running
219          *
220          * @param integer $priority The priority that should be checked
221          *
222          * @return integer Is there a process running with that priority?
223          * @throws \Exception
224          */
225         private static function processWithPriorityActive($priority)
226         {
227                 $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
228                 return DBA::exists('workerqueue', $condition);
229         }
230
231         /**
232          * @brief Execute a worker entry
233          *
234          * @param array $queue Workerqueue entry
235          *
236          * @return boolean "true" if further processing should be stopped
237          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238          */
239         public static function execute($queue)
240         {
241                 $a = \get_app();
242
243                 $mypid = getmypid();
244
245                 // Quit when in maintenance
246                 if (Config::get('system', 'maintenance', false, true)) {
247                         Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
248                         return false;
249                 }
250
251                 // Constantly check the number of parallel database processes
252                 if ($a->isMaxProcessesReached()) {
253                         Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
254                         return false;
255                 }
256
257                 // Constantly check the number of available database connections to let the frontend be accessible at any time
258                 if (self::maxConnectionsReached()) {
259                         Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
260                         return false;
261                 }
262
263                 $argv = json_decode($queue["parameter"], true);
264
265                 // Check for existance and validity of the include file
266                 $include = $argv[0];
267
268                 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
269                         // We constantly update the "executed" date every minute to avoid being killed too soon
270                         if (!isset(self::$last_update)) {
271                                 self::$last_update = strtotime($queue["executed"]);
272                         }
273
274                         $age = (time() - self::$last_update) / 60;
275                         self::$last_update = time();
276
277                         if ($age > 1) {
278                                 $stamp = (float)microtime(true);
279                                 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
280                                 self::$db_duration += (microtime(true) - $stamp);
281                                 self::$db_duration_write += (microtime(true) - $stamp);
282                         }
283
284                         array_shift($argv);
285
286                         self::execFunction($queue, $include, $argv, true);
287
288                         $stamp = (float)microtime(true);
289                         $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
290                         if (DBA::update('workerqueue', ['done' => true], $condition)) {
291                                 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
292                         }
293                         self::$db_duration = (microtime(true) - $stamp);
294                         self::$db_duration_write += (microtime(true) - $stamp);
295
296                         return true;
297                 }
298
299                 // The script could be provided as full path or only with the function name
300                 if ($include == basename($include)) {
301                         $include = "include/".$include.".php";
302                 }
303
304                 if (!validate_include($include)) {
305                         Logger::log("Include file ".$argv[0]." is not valid!");
306                         $stamp = (float)microtime(true);
307                         DBA::delete('workerqueue', ['id' => $queue["id"]]);
308                         self::$db_duration = (microtime(true) - $stamp);
309                         self::$db_duration_write += (microtime(true) - $stamp);
310                         return true;
311                 }
312
313                 require_once $include;
314
315                 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
316
317                 if (function_exists($funcname)) {
318                         // We constantly update the "executed" date every minute to avoid being killed too soon
319                         if (!isset(self::$last_update)) {
320                                 self::$last_update = strtotime($queue["executed"]);
321                         }
322
323                         $age = (time() - self::$last_update) / 60;
324                         self::$last_update = time();
325
326                         if ($age > 1) {
327                                 $stamp = (float)microtime(true);
328                                 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
329                                 self::$db_duration += (microtime(true) - $stamp);
330                                 self::$db_duration_write += (microtime(true) - $stamp);
331                         }
332
333                         self::execFunction($queue, $funcname, $argv, false);
334
335                         $stamp = (float)microtime(true);
336                         if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
337                                 Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
338                         }
339                         self::$db_duration = (microtime(true) - $stamp);
340                         self::$db_duration_write += (microtime(true) - $stamp);
341                 } else {
342                         Logger::log("Function ".$funcname." does not exist");
343                         $stamp = (float)microtime(true);
344                         DBA::delete('workerqueue', ['id' => $queue["id"]]);
345                         self::$db_duration = (microtime(true) - $stamp);
346                         self::$db_duration_write += (microtime(true) - $stamp);
347                 }
348
349                 return true;
350         }
351
352         /**
353          * @brief Execute a function from the queue
354          *
355          * @param array   $queue       Workerqueue entry
356          * @param string  $funcname    name of the function
357          * @param array   $argv        Array of values to be passed to the function
358          * @param boolean $method_call boolean
359          * @return void
360          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
361          */
362         private static function execFunction($queue, $funcname, $argv, $method_call)
363         {
364                 $a = \get_app();
365
366                 $mypid = getmypid();
367
368                 $argc = count($argv);
369
370                 $new_process_id = System::processID("wrk");
371
372                 Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
373
374                 $stamp = (float)microtime(true);
375
376                 // We use the callstack here to analyze the performance of executed worker entries.
377                 // For this reason the variables have to be initialized.
378                 if (Config::get("system", "profiler")) {
379                         $a->performance["start"] = microtime(true);
380                         $a->performance["database"] = 0;
381                         $a->performance["database_write"] = 0;
382                         $a->performance["cache"] = 0;
383                         $a->performance["cache_write"] = 0;
384                         $a->performance["network"] = 0;
385                         $a->performance["file"] = 0;
386                         $a->performance["rendering"] = 0;
387                         $a->performance["parser"] = 0;
388                         $a->performance["marktime"] = 0;
389                         $a->performance["markstart"] = microtime(true);
390                         $a->callstack = [];
391                 }
392
393                 // For better logging create a new process id for every worker call
394                 // But preserve the old one for the worker
395                 $old_process_id = $a->process_id;
396                 $a->process_id = $new_process_id;
397                 $a->queue = $queue;
398
399                 $up_duration = microtime(true) - self::$up_start;
400
401                 // Reset global data to avoid interferences
402                 unset($_SESSION);
403
404                 if ($method_call) {
405                         call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
406                 } else {
407                         $funcname($argv, $argc);
408                 }
409
410                 $a->process_id = $old_process_id;
411                 unset($a->queue);
412
413                 $duration = (microtime(true) - $stamp);
414
415                 /* With these values we can analyze how effective the worker is.
416                  * The database and rest time should be low since this is the unproductive time.
417                  * The execution time is the productive time.
418                  * By changing parameters like the maximum number of workers we can check the effectivness.
419                 */
420                 Logger::log(
421                         'DB: '.number_format(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 4).
422                         ' - DB-Count: '.number_format(self::$db_duration_count, 4).
423                         ' - DB-Stat: '.number_format(self::$db_duration_stat, 4).
424                         ' - DB-Write: '.number_format(self::$db_duration_write, 4).
425                         ' - Lock: '.number_format(self::$lock_duration, 4).
426                         ' - Rest: '.number_format(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 4).
427                         ' - Execution: '.number_format($duration, 4),
428                         Logger::DEBUG
429                 );
430
431                 self::$up_start = microtime(true);
432                 self::$db_duration = 0;
433                 self::$db_duration_count = 0;
434                 self::$db_duration_stat = 0;
435                 self::$db_duration_write = 0;
436                 self::$lock_duration = 0;
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 ".$duration." 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          * @param integer $entries Total number of queue entries
688          * @param integer $deferred Number of deferred queue entries
689          *
690          * @return bool Are there too much workers running?
691          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
692          */
693         public static function tooMuchWorkers($entries = 0, $deferred = 0)
694         {
695                 $queues = Config::get("system", "worker_queues", 4);
696
697                 $maxqueues = $queues;
698
699                 $active = self::activeWorkers();
700
701                 // Decrease the number of workers at higher load
702                 $load = System::currentLoad();
703                 if ($load) {
704                         $maxsysload = intval(Config::get("system", "maxloadavg", 50));
705
706                         /* Default exponent 3 causes queues to rapidly decrease as load increases.
707                          * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
708                          * For some environments, this rapid decrease is not needed.
709                          * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
710                          */
711                         $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
712                         $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
713                         $queues = intval(ceil($slope * $maxqueues));
714
715                         $processlist = '';
716
717                         if (Config::get('system', 'worker_jpm')) {
718                                 $intervals = explode(',', Config::get('system', 'worker_jpm_range'));
719                                 $jobs_per_minute = [];
720                                 foreach ($intervals as $interval) {
721                                         $stamp = (float)microtime(true);
722                                         $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
723                                         self::$db_duration += (microtime(true) - $stamp);
724                                         self::$db_duration_stat += (microtime(true) - $stamp);
725                                         if ($job = DBA::fetch($jobs)) {
726                                                 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
727                                         }
728                                         DBA::close($jobs);
729                                 }
730                                 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
731                         }
732
733                         // Create a list of queue entries grouped by their priority
734                         $listitem = [0 => ''];
735
736                         $idle_workers = $active;
737
738                         if (Config::get('system', 'worker_debug')) {
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                                                 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
752                                         }
753                                         DBA::close($processes);
754                                 }
755                                 DBA::close($jobs);
756                         } else {
757                                 $stamp = (float)microtime(true);
758                                 $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`");
759                                 self::$db_duration += (microtime(true) - $stamp);
760
761                                 while ($entry = DBA::fetch($jobs)) {
762                                         $idle_workers -= $entry["running"];
763                                         $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
764                                 }
765                                 DBA::close($jobs);
766                         }
767
768                         $listitem[0] = "0:" . max(0, $idle_workers);
769
770                         $processlist .= ' ('.implode(', ', $listitem).')';
771
772                         if (empty($deferred) && empty($entries)) {
773                                 $deferred = self::deferredEntries();
774                                 $entries = max(self::totalEntries() - $deferred, 0);
775                         }
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 . "/" . ($entries - $deferred) . $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         /**
823          * @brief Check if we should pass some slow processes
824          *
825          * When the active processes of the highest priority are using more than 2/3
826          * of all processes, we let pass slower processes.
827          *
828          * @param string $highest_priority Returns the currently highest priority
829          * @return bool We let pass a slower process than $highest_priority
830          * @throws \Exception
831          */
832         private static function passingSlow(&$highest_priority)
833         {
834                 $highest_priority = 0;
835
836                 $stamp = (float)microtime(true);
837                 $r = DBA::p(
838                         "SELECT `priority`
839                                 FROM `process`
840                                 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
841                 );
842                 self::$db_duration += (microtime(true) - $stamp);
843
844                 // No active processes at all? Fine
845                 if (!DBA::isResult($r)) {
846                         return false;
847                 }
848                 $priorities = [];
849                 while ($line = DBA::fetch($r)) {
850                         $priorities[] = $line["priority"];
851                 }
852                 DBA::close($r);
853
854                 // Should not happen
855                 if (count($priorities) == 0) {
856                         return false;
857                 }
858                 $highest_priority = min($priorities);
859
860                 // The highest process is already the slowest one?
861                 // Then we quit
862                 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
863                         return false;
864                 }
865                 $high = 0;
866                 foreach ($priorities as $priority) {
867                         if ($priority == $highest_priority) {
868                                 ++$high;
869                         }
870                 }
871                 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
872                 $passing_slow = (($high/count($priorities)) > (2/3));
873
874                 if ($passing_slow) {
875                         Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
876                 }
877                 return $passing_slow;
878         }
879
880         /**
881          * @brief Find and claim the next worker process for us
882          *
883          * @param boolean $passing_slow Returns if we had passed low priority processes
884          * @param integer $entries Total number of queue entries
885          * @param integer $deferred Number of deferred queue entries
886          * @return boolean Have we found something?
887          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
888          */
889         private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
890         {
891                 $mypid = getmypid();
892
893                 // Check if we should pass some low priority process
894                 $highest_priority = 0;
895                 $found = false;
896                 $passing_slow = false;
897
898                 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
899                 // We decrease the limit with the number of entries left in the queue
900                 $worker_queues = Config::get("system", "worker_queues", 4);
901                 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
902                 $lower_job_limit = $worker_queues * $queue_length * 2;
903                 $entries = max($entries - $deferred, 0);
904
905                 // Now do some magic
906                 $exponent = 2;
907                 $slope = $queue_length / pow($lower_job_limit, $exponent);
908                 $limit = min($queue_length, ceil($slope * pow($entries, $exponent)));
909
910                 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $entries . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
911                 $ids = [];
912                 if (self::passingSlow($highest_priority)) {
913                         // Are there waiting processes with a higher priority than the currently highest?
914                         $stamp = (float)microtime(true);
915                         $result = DBA::select(
916                                 'workerqueue',
917                                 ['id'],
918                                 ["`pid` = 0 AND `priority` < ? AND NOT `done` AND `next_try` < ?",
919                                 $highest_priority, DateTimeFormat::utcNow()],
920                                 ['limit' => $limit, 'order' => ['priority', 'created']]
921                         );
922                         self::$db_duration += (microtime(true) - $stamp);
923
924                         while ($id = DBA::fetch($result)) {
925                                 $ids[] = $id["id"];
926                         }
927                         DBA::close($result);
928
929                         $found = (count($ids) > 0);
930
931                         if (!$found) {
932                                 // Give slower processes some processing time
933                                 $stamp = (float)microtime(true);
934                                 $result = DBA::select(
935                                         'workerqueue',
936                                         ['id'],
937                                         ["`pid` = 0 AND `priority` > ? AND NOT `done` AND `next_try` < ?",
938                                         $highest_priority, DateTimeFormat::utcNow()],
939                                         ['limit' => $limit, 'order' => ['priority', 'created']]
940                                 );
941                                 self::$db_duration += (microtime(true) - $stamp);
942
943                                 while ($id = DBA::fetch($result)) {
944                                         $ids[] = $id["id"];
945                                 }
946                                 DBA::close($result);
947
948                                 $found = (count($ids) > 0);
949                                 $passing_slow = $found;
950                         }
951                 }
952
953                 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
954                 if (!$found) {
955                         $stamp = (float)microtime(true);
956                         $result = DBA::select(
957                                 'workerqueue',
958                                 ['id'],
959                                 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
960                                 DateTimeFormat::utcNow()],
961                                 ['limit' => $limit, 'order' => ['priority', 'created']]
962                         );
963                         self::$db_duration += (microtime(true) - $stamp);
964
965                         while ($id = DBA::fetch($result)) {
966                                 $ids[] = $id["id"];
967                         }
968                         DBA::close($result);
969
970                         $found = (count($ids) > 0);
971                 }
972
973                 if ($found) {
974                         $stamp = (float)microtime(true);
975                         $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
976                         array_unshift($ids, $condition);
977                         DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
978                         self::$db_duration += (microtime(true) - $stamp);
979                         self::$db_duration_write += (microtime(true) - $stamp);
980                 }
981
982                 return $found;
983         }
984
985         /**
986          * @brief Returns the next worker process
987          *
988          * @param boolean $passing_slow Returns if we had passed low priority processes
989          * @param integer $entries Returns total number of queue entries
990          * @param integer $deferred Returns number of deferred queue entries
991          *
992          * @return string SQL statement
993          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994          */
995         public static function workerProcess(&$passing_slow, &$entries, &$deferred)
996         {
997                 // There can already be jobs for us in the queue.
998                 $stamp = (float)microtime(true);
999                 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1000                 self::$db_duration += (microtime(true) - $stamp);
1001                 if (DBA::isResult($r)) {
1002                         return DBA::toArray($r);
1003                 }
1004                 DBA::close($r);
1005
1006                 // Counting the rows outside the lock reduces the lock time
1007                 $entries = self::totalEntries();
1008                 $deferred = self::deferredEntries();
1009
1010                 $stamp = (float)microtime(true);
1011                 if (!Lock::acquire('worker_process')) {
1012                         return false;
1013                 }
1014                 self::$lock_duration += (microtime(true) - $stamp);
1015
1016                 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
1017
1018                 Lock::release('worker_process');
1019
1020                 if ($found) {
1021                         $stamp = (float)microtime(true);
1022                         $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1023                         self::$db_duration += (microtime(true) - $stamp);
1024                         return DBA::toArray($r);
1025                 }
1026                 return false;
1027         }
1028
1029         /**
1030          * @brief Removes a workerqueue entry from the current process
1031          * @return void
1032          * @throws \Exception
1033          */
1034         public static function unclaimProcess()
1035         {
1036                 $mypid = getmypid();
1037
1038                 $stamp = (float)microtime(true);
1039                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1040                 self::$db_duration += (microtime(true) - $stamp);
1041                 self::$db_duration_write += (microtime(true) - $stamp);
1042         }
1043
1044         /**
1045          * @brief Call the front end worker
1046          * @return void
1047          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1048          */
1049         public static function callWorker()
1050         {
1051                 if (!Config::get("system", "frontend_worker")) {
1052                         return;
1053                 }
1054
1055                 $url = System::baseUrl()."/worker";
1056                 Network::fetchUrl($url, false, $redirects, 1);
1057         }
1058
1059         /**
1060          * @brief Call the front end worker if there aren't any active
1061          * @return void
1062          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1063          */
1064         public static function executeIfIdle()
1065         {
1066                 if (!Config::get("system", "frontend_worker")) {
1067                         return;
1068                 }
1069
1070                 // Do we have "proc_open"? Then we can fork the worker
1071                 if (function_exists("proc_open")) {
1072                         // When was the last time that we called the worker?
1073                         // Less than one minute? Then we quit
1074                         if ((time() - Config::get("system", "worker_started")) < 60) {
1075                                 return;
1076                         }
1077
1078                         Config::set("system", "worker_started", time());
1079
1080                         // Do we have enough running workers? Then we quit here.
1081                         if (self::tooMuchWorkers()) {
1082                                 // Cleaning dead processes
1083                                 self::killStaleWorkers();
1084                                 Process::deleteInactive();
1085
1086                                 return;
1087                         }
1088
1089                         self::runCron();
1090
1091                         Logger::log('Call worker', Logger::DEBUG);
1092                         self::spawnWorker();
1093                         return;
1094                 }
1095
1096                 // We cannot execute background processes.
1097                 // We now run the processes from the frontend.
1098                 // This won't work with long running processes.
1099                 self::runCron();
1100
1101                 self::clearProcesses();
1102
1103                 $workers = self::activeWorkers();
1104
1105                 if ($workers == 0) {
1106                         self::callWorker();
1107                 }
1108         }
1109
1110         /**
1111          * @brief Removes long running worker processes
1112          * @return void
1113          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1114          */
1115         public static function clearProcesses()
1116         {
1117                 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1118
1119                 /// @todo We should clean up the corresponding workerqueue entries as well
1120                 $stamp = (float)microtime(true);
1121                 $condition = ["`created` < ? AND `command` = 'worker.php'",
1122                                 DateTimeFormat::utc("now - ".$timeout." minutes")];
1123                 DBA::delete('process', $condition);
1124                 self::$db_duration = (microtime(true) - $stamp);
1125                 self::$db_duration_write += (microtime(true) - $stamp);
1126         }
1127
1128         /**
1129          * @brief Runs the cron processes
1130          * @return void
1131          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132          */
1133         private static function runCron()
1134         {
1135                 Logger::log('Add cron entries', Logger::DEBUG);
1136
1137                 // Check for spooled items
1138                 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1139
1140                 // Run the cron job that calls all other jobs
1141                 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1142
1143                 // Cleaning dead processes
1144                 self::killStaleWorkers();
1145         }
1146
1147         /**
1148          * @brief Spawns a new worker
1149          * @param bool $do_cron
1150          * @return void
1151          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1152          */
1153         public static function spawnWorker($do_cron = false)
1154         {
1155                 $command = 'bin/worker.php';
1156
1157                 $args = ['no_cron' => !$do_cron];
1158
1159                 get_app()->proc_run($command, $args);
1160
1161                 // after spawning we have to remove the flag.
1162                 if (Config::get('system', 'worker_daemon_mode', false)) {
1163                         self::IPCSetJobState(false);
1164                 }
1165         }
1166
1167         /**
1168          * @brief Adds tasks to the worker queue
1169          *
1170          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1171          *
1172          * next args are passed as $cmd command line
1173          * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1174          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1175          *
1176          * @return boolean "false" if proc_run couldn't be executed
1177          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1178          * @note $cmd and string args are surrounded with ""
1179          *
1180          * @hooks 'proc_run'
1181          *    array $arr
1182          *
1183          */
1184         public static function add($cmd)
1185         {
1186                 $args = func_get_args();
1187
1188                 if (!count($args)) {
1189                         return false;
1190                 }
1191
1192                 $arr = ['args' => $args, 'run_cmd' => true];
1193
1194                 Hook::callAll("proc_run", $arr);
1195                 if (!$arr['run_cmd'] || !count($args)) {
1196                         return true;
1197                 }
1198
1199                 $priority = PRIORITY_MEDIUM;
1200                 $dont_fork = Config::get("system", "worker_dont_fork", false);
1201                 $created = DateTimeFormat::utcNow();
1202                 $force_priority = false;
1203
1204                 $run_parameter = array_shift($args);
1205
1206                 if (is_int($run_parameter)) {
1207                         $priority = $run_parameter;
1208                 } elseif (is_array($run_parameter)) {
1209                         if (isset($run_parameter['priority'])) {
1210                                 $priority = $run_parameter['priority'];
1211                         }
1212                         if (isset($run_parameter['created'])) {
1213                                 $created = $run_parameter['created'];
1214                         }
1215                         if (isset($run_parameter['dont_fork'])) {
1216                                 $dont_fork = $run_parameter['dont_fork'];
1217                         }
1218                         if (isset($run_parameter['force_priority'])) {
1219                                 $force_priority = $run_parameter['force_priority'];
1220                         }
1221                 }
1222
1223                 $parameters = json_encode($args);
1224                 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1225
1226                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1227                 if (DBA::errorNo() != 0) {
1228                         return false;
1229                 }
1230
1231                 if (!$found) {
1232                         DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1233                 } elseif ($force_priority) {
1234                         DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1235                 }
1236
1237                 // Should we quit and wait for the worker to be called as a cronjob?
1238                 if ($dont_fork) {
1239                         return true;
1240                 }
1241
1242                 // If there is a lock then we don't have to check for too much worker
1243                 if (!Lock::acquire('worker', 0)) {
1244                         return true;
1245                 }
1246
1247                 // If there are already enough workers running, don't fork another one
1248                 $quit = self::tooMuchWorkers();
1249                 Lock::release('worker');
1250
1251                 if ($quit) {
1252                         return true;
1253                 }
1254
1255                 // We tell the daemon that a new job entry exists
1256                 if (Config::get('system', 'worker_daemon_mode', false)) {
1257                         // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1258                         return true;
1259                 }
1260
1261                 // Now call the worker to execute the jobs that we just added to the queue
1262                 self::spawnWorker();
1263
1264                 return true;
1265         }
1266
1267         /**
1268          * Defers the current worker entry
1269          */
1270         public static function defer()
1271         {
1272                 if (empty(BaseObject::getApp()->queue)) {
1273                         return;
1274                 }
1275
1276                 $queue = BaseObject::getApp()->queue;
1277
1278                 $retrial = $queue['retrial'];
1279                 $id = $queue['id'];
1280                 $priority = $queue['priority'];
1281
1282                 if ($retrial > 14) {
1283                         Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1284                         return;
1285                 }
1286
1287                 // Calculate the delay until the next trial
1288                 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1289                 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1290
1291                 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1292                         $priority = PRIORITY_MEDIUM;
1293                 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1294                         $priority = PRIORITY_LOW;
1295                 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1296                         $priority = PRIORITY_NEGLIGIBLE;
1297                 }
1298
1299                 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1300
1301                 $stamp = (float)microtime(true);
1302                 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1303                 DBA::update('workerqueue', $fields, ['id' => $id]);
1304                 self::$db_duration += (microtime(true) - $stamp);
1305                 self::$db_duration_write += (microtime(true) - $stamp);
1306         }
1307
1308         /**
1309          * Log active processes into the "process" table
1310          *
1311          * @brief Log active processes into the "process" table
1312          */
1313         public static function startProcess()
1314         {
1315                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1316
1317                 $command = basename($trace[0]['file']);
1318
1319                 Process::deleteInactive();
1320
1321                 Process::insert($command);
1322         }
1323
1324         /**
1325          * Remove the active process from the "process" table
1326          *
1327          * @brief Remove the active process from the "process" table
1328          * @return bool
1329          * @throws \Exception
1330          */
1331         public static function endProcess()
1332         {
1333                 return Process::deleteByPid();
1334         }
1335
1336         /**
1337          * Set the flag if some job is waiting
1338          *
1339          * @brief Set the flag if some job is waiting
1340          * @param boolean $jobs Is there a waiting job?
1341          * @throws \Exception
1342          */
1343         public static function IPCSetJobState($jobs)
1344         {
1345                 $stamp = (float)microtime(true);
1346                 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1347                 self::$db_duration += (microtime(true) - $stamp);
1348                 self::$db_duration_write += (microtime(true) - $stamp);
1349         }
1350
1351         /**
1352          * Checks if some worker job waits to be executed
1353          *
1354          * @brief Checks if some worker job waits to be executed
1355          * @return bool
1356          * @throws \Exception
1357          */
1358         public static function IPCJobsExists()
1359         {
1360                 $stamp = (float)microtime(true);
1361                 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1362                 self::$db_duration += (microtime(true) - $stamp);
1363
1364                 // When we don't have a row, no job is running
1365                 if (!DBA::isResult($row)) {
1366                         return false;
1367                 }
1368
1369                 return (bool)$row['jobs'];
1370         }
1371 }