]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
Merge pull request #6637 from annando/fix-jpm
[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                                         if ($interval == 0) {
722                                                 continue;
723                                         } else {
724                                                 $interval = (int)$interval;
725                                         }
726
727                                         $stamp = (float)microtime(true);
728                                         $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
729                                         self::$db_duration += (microtime(true) - $stamp);
730                                         self::$db_duration_stat += (microtime(true) - $stamp);
731                                         if ($job = DBA::fetch($jobs)) {
732                                                 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
733                                         }
734                                         DBA::close($jobs);
735                                 }
736                                 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
737                         }
738
739                         // Create a list of queue entries grouped by their priority
740                         $listitem = [0 => ''];
741
742                         $idle_workers = $active;
743
744                         if (Config::get('system', 'worker_debug')) {
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                                                 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
758                                         }
759                                         DBA::close($processes);
760                                 }
761                                 DBA::close($jobs);
762                         } else {
763                                 $stamp = (float)microtime(true);
764                                 $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`");
765                                 self::$db_duration += (microtime(true) - $stamp);
766
767                                 while ($entry = DBA::fetch($jobs)) {
768                                         $idle_workers -= $entry["running"];
769                                         $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
770                                 }
771                                 DBA::close($jobs);
772                         }
773
774                         $listitem[0] = "0:" . max(0, $idle_workers);
775
776                         $processlist .= ' ('.implode(', ', $listitem).')';
777
778                         if (empty($deferred) && empty($entries)) {
779                                 $deferred = self::deferredEntries();
780                                 $entries = max(self::totalEntries() - $deferred, 0);
781                         }
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 . "/" . ($entries - $deferred) . $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 Check if we should pass some slow processes
830          *
831          * When the active processes of the highest priority are using more than 2/3
832          * of all processes, we let pass slower processes.
833          *
834          * @param string $highest_priority Returns the currently highest priority
835          * @return bool We let pass a slower process than $highest_priority
836          * @throws \Exception
837          */
838         private static function passingSlow(&$highest_priority)
839         {
840                 $highest_priority = 0;
841
842                 $stamp = (float)microtime(true);
843                 $r = DBA::p(
844                         "SELECT `priority`
845                                 FROM `process`
846                                 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
847                 );
848                 self::$db_duration += (microtime(true) - $stamp);
849
850                 // No active processes at all? Fine
851                 if (!DBA::isResult($r)) {
852                         return false;
853                 }
854                 $priorities = [];
855                 while ($line = DBA::fetch($r)) {
856                         $priorities[] = $line["priority"];
857                 }
858                 DBA::close($r);
859
860                 // Should not happen
861                 if (count($priorities) == 0) {
862                         return false;
863                 }
864                 $highest_priority = min($priorities);
865
866                 // The highest process is already the slowest one?
867                 // Then we quit
868                 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
869                         return false;
870                 }
871                 $high = 0;
872                 foreach ($priorities as $priority) {
873                         if ($priority == $highest_priority) {
874                                 ++$high;
875                         }
876                 }
877                 Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
878                 $passing_slow = (($high/count($priorities)) > (2/3));
879
880                 if ($passing_slow) {
881                         Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
882                 }
883                 return $passing_slow;
884         }
885
886         /**
887          * @brief Find and claim the next worker process for us
888          *
889          * @param boolean $passing_slow Returns if we had passed low priority processes
890          * @param integer $entries Total number of queue entries
891          * @param integer $deferred Number of deferred queue entries
892          * @return boolean Have we found something?
893          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
894          */
895         private static function findWorkerProcesses(&$passing_slow, $entries, $deferred)
896         {
897                 $mypid = getmypid();
898
899                 // Check if we should pass some low priority process
900                 $highest_priority = 0;
901                 $found = false;
902                 $passing_slow = false;
903
904                 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
905                 // We decrease the limit with the number of entries left in the queue
906                 $worker_queues = Config::get("system", "worker_queues", 4);
907                 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
908                 $lower_job_limit = $worker_queues * $queue_length * 2;
909                 $entries = max($entries - $deferred, 0);
910
911                 // Now do some magic
912                 $exponent = 2;
913                 $slope = $queue_length / pow($lower_job_limit, $exponent);
914                 $limit = min($queue_length, ceil($slope * pow($entries, $exponent)));
915
916                 Logger::log('Deferred: ' . $deferred . ' - Total: ' . $entries . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
917                 $ids = [];
918                 if (self::passingSlow($highest_priority)) {
919                         // Are there waiting processes with a higher priority than the currently highest?
920                         $stamp = (float)microtime(true);
921                         $result = DBA::select(
922                                 'workerqueue',
923                                 ['id'],
924                                 ["`pid` = 0 AND `priority` < ? AND NOT `done` AND `next_try` < ?",
925                                 $highest_priority, DateTimeFormat::utcNow()],
926                                 ['limit' => $limit, 'order' => ['priority', 'created']]
927                         );
928                         self::$db_duration += (microtime(true) - $stamp);
929
930                         while ($id = DBA::fetch($result)) {
931                                 $ids[] = $id["id"];
932                         }
933                         DBA::close($result);
934
935                         $found = (count($ids) > 0);
936
937                         if (!$found) {
938                                 // Give slower processes some processing time
939                                 $stamp = (float)microtime(true);
940                                 $result = DBA::select(
941                                         'workerqueue',
942                                         ['id'],
943                                         ["`pid` = 0 AND `priority` > ? AND NOT `done` AND `next_try` < ?",
944                                         $highest_priority, DateTimeFormat::utcNow()],
945                                         ['limit' => $limit, 'order' => ['priority', 'created']]
946                                 );
947                                 self::$db_duration += (microtime(true) - $stamp);
948
949                                 while ($id = DBA::fetch($result)) {
950                                         $ids[] = $id["id"];
951                                 }
952                                 DBA::close($result);
953
954                                 $found = (count($ids) > 0);
955                                 $passing_slow = $found;
956                         }
957                 }
958
959                 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
960                 if (!$found) {
961                         $stamp = (float)microtime(true);
962                         $result = DBA::select(
963                                 'workerqueue',
964                                 ['id'],
965                                 ["`pid` = 0 AND NOT `done` AND `next_try` < ?",
966                                 DateTimeFormat::utcNow()],
967                                 ['limit' => $limit, 'order' => ['priority', 'created']]
968                         );
969                         self::$db_duration += (microtime(true) - $stamp);
970
971                         while ($id = DBA::fetch($result)) {
972                                 $ids[] = $id["id"];
973                         }
974                         DBA::close($result);
975
976                         $found = (count($ids) > 0);
977                 }
978
979                 if ($found) {
980                         $stamp = (float)microtime(true);
981                         $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
982                         array_unshift($ids, $condition);
983                         DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $mypid], $ids);
984                         self::$db_duration += (microtime(true) - $stamp);
985                         self::$db_duration_write += (microtime(true) - $stamp);
986                 }
987
988                 return $found;
989         }
990
991         /**
992          * @brief Returns the next worker process
993          *
994          * @param boolean $passing_slow Returns if we had passed low priority processes
995          * @param integer $entries Returns total number of queue entries
996          * @param integer $deferred Returns number of deferred queue entries
997          *
998          * @return string SQL statement
999          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1000          */
1001         public static function workerProcess(&$passing_slow, &$entries, &$deferred)
1002         {
1003                 // There can already be jobs for us in the queue.
1004                 $stamp = (float)microtime(true);
1005                 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1006                 self::$db_duration += (microtime(true) - $stamp);
1007                 if (DBA::isResult($r)) {
1008                         return DBA::toArray($r);
1009                 }
1010                 DBA::close($r);
1011
1012                 // Counting the rows outside the lock reduces the lock time
1013                 $entries = self::totalEntries();
1014                 $deferred = self::deferredEntries();
1015
1016                 $stamp = (float)microtime(true);
1017                 if (!Lock::acquire('worker_process')) {
1018                         return false;
1019                 }
1020                 self::$lock_duration += (microtime(true) - $stamp);
1021
1022                 $found = self::findWorkerProcesses($passing_slow, $entries, $deferred);
1023
1024                 Lock::release('worker_process');
1025
1026                 if ($found) {
1027                         $stamp = (float)microtime(true);
1028                         $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
1029                         self::$db_duration += (microtime(true) - $stamp);
1030                         return DBA::toArray($r);
1031                 }
1032                 return false;
1033         }
1034
1035         /**
1036          * @brief Removes a workerqueue entry from the current process
1037          * @return void
1038          * @throws \Exception
1039          */
1040         public static function unclaimProcess()
1041         {
1042                 $mypid = getmypid();
1043
1044                 $stamp = (float)microtime(true);
1045                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1046                 self::$db_duration += (microtime(true) - $stamp);
1047                 self::$db_duration_write += (microtime(true) - $stamp);
1048         }
1049
1050         /**
1051          * @brief Call the front end worker
1052          * @return void
1053          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1054          */
1055         public static function callWorker()
1056         {
1057                 if (!Config::get("system", "frontend_worker")) {
1058                         return;
1059                 }
1060
1061                 $url = System::baseUrl()."/worker";
1062                 Network::fetchUrl($url, false, $redirects, 1);
1063         }
1064
1065         /**
1066          * @brief Call the front end worker if there aren't any active
1067          * @return void
1068          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1069          */
1070         public static function executeIfIdle()
1071         {
1072                 if (!Config::get("system", "frontend_worker")) {
1073                         return;
1074                 }
1075
1076                 // Do we have "proc_open"? Then we can fork the worker
1077                 if (function_exists("proc_open")) {
1078                         // When was the last time that we called the worker?
1079                         // Less than one minute? Then we quit
1080                         if ((time() - Config::get("system", "worker_started")) < 60) {
1081                                 return;
1082                         }
1083
1084                         Config::set("system", "worker_started", time());
1085
1086                         // Do we have enough running workers? Then we quit here.
1087                         if (self::tooMuchWorkers()) {
1088                                 // Cleaning dead processes
1089                                 self::killStaleWorkers();
1090                                 Process::deleteInactive();
1091
1092                                 return;
1093                         }
1094
1095                         self::runCron();
1096
1097                         Logger::log('Call worker', Logger::DEBUG);
1098                         self::spawnWorker();
1099                         return;
1100                 }
1101
1102                 // We cannot execute background processes.
1103                 // We now run the processes from the frontend.
1104                 // This won't work with long running processes.
1105                 self::runCron();
1106
1107                 self::clearProcesses();
1108
1109                 $workers = self::activeWorkers();
1110
1111                 if ($workers == 0) {
1112                         self::callWorker();
1113                 }
1114         }
1115
1116         /**
1117          * @brief Removes long running worker processes
1118          * @return void
1119          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1120          */
1121         public static function clearProcesses()
1122         {
1123                 $timeout = Config::get("system", "frontend_worker_timeout", 10);
1124
1125                 /// @todo We should clean up the corresponding workerqueue entries as well
1126                 $stamp = (float)microtime(true);
1127                 $condition = ["`created` < ? AND `command` = 'worker.php'",
1128                                 DateTimeFormat::utc("now - ".$timeout." minutes")];
1129                 DBA::delete('process', $condition);
1130                 self::$db_duration = (microtime(true) - $stamp);
1131                 self::$db_duration_write += (microtime(true) - $stamp);
1132         }
1133
1134         /**
1135          * @brief Runs the cron processes
1136          * @return void
1137          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1138          */
1139         private static function runCron()
1140         {
1141                 Logger::log('Add cron entries', Logger::DEBUG);
1142
1143                 // Check for spooled items
1144                 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1145
1146                 // Run the cron job that calls all other jobs
1147                 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1148
1149                 // Cleaning dead processes
1150                 self::killStaleWorkers();
1151         }
1152
1153         /**
1154          * @brief Spawns a new worker
1155          * @param bool $do_cron
1156          * @return void
1157          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1158          */
1159         public static function spawnWorker($do_cron = false)
1160         {
1161                 $command = 'bin/worker.php';
1162
1163                 $args = ['no_cron' => !$do_cron];
1164
1165                 get_app()->proc_run($command, $args);
1166
1167                 // after spawning we have to remove the flag.
1168                 if (Config::get('system', 'worker_daemon_mode', false)) {
1169                         self::IPCSetJobState(false);
1170                 }
1171         }
1172
1173         /**
1174          * @brief Adds tasks to the worker queue
1175          *
1176          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1177          *
1178          * next args are passed as $cmd command line
1179          * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
1180          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
1181          *
1182          * @return boolean "false" if proc_run couldn't be executed
1183          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1184          * @note $cmd and string args are surrounded with ""
1185          *
1186          * @hooks 'proc_run'
1187          *    array $arr
1188          *
1189          */
1190         public static function add($cmd)
1191         {
1192                 $args = func_get_args();
1193
1194                 if (!count($args)) {
1195                         return false;
1196                 }
1197
1198                 $arr = ['args' => $args, 'run_cmd' => true];
1199
1200                 Hook::callAll("proc_run", $arr);
1201                 if (!$arr['run_cmd'] || !count($args)) {
1202                         return true;
1203                 }
1204
1205                 $priority = PRIORITY_MEDIUM;
1206                 $dont_fork = Config::get("system", "worker_dont_fork", false);
1207                 $created = DateTimeFormat::utcNow();
1208                 $force_priority = false;
1209
1210                 $run_parameter = array_shift($args);
1211
1212                 if (is_int($run_parameter)) {
1213                         $priority = $run_parameter;
1214                 } elseif (is_array($run_parameter)) {
1215                         if (isset($run_parameter['priority'])) {
1216                                 $priority = $run_parameter['priority'];
1217                         }
1218                         if (isset($run_parameter['created'])) {
1219                                 $created = $run_parameter['created'];
1220                         }
1221                         if (isset($run_parameter['dont_fork'])) {
1222                                 $dont_fork = $run_parameter['dont_fork'];
1223                         }
1224                         if (isset($run_parameter['force_priority'])) {
1225                                 $force_priority = $run_parameter['force_priority'];
1226                         }
1227                 }
1228
1229                 $parameters = json_encode($args);
1230                 $found = DBA::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
1231
1232                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1233                 if (DBA::errorNo() != 0) {
1234                         return false;
1235                 }
1236
1237                 if (!$found) {
1238                         DBA::insert('workerqueue', ['parameter' => $parameters, 'created' => $created, 'priority' => $priority]);
1239                 } elseif ($force_priority) {
1240                         DBA::update('workerqueue', ['priority' => $priority], ['parameter' => $parameters, 'done' => false, 'pid' => 0]);
1241                 }
1242
1243                 // Should we quit and wait for the worker to be called as a cronjob?
1244                 if ($dont_fork) {
1245                         return true;
1246                 }
1247
1248                 // If there is a lock then we don't have to check for too much worker
1249                 if (!Lock::acquire('worker', 0)) {
1250                         return true;
1251                 }
1252
1253                 // If there are already enough workers running, don't fork another one
1254                 $quit = self::tooMuchWorkers();
1255                 Lock::release('worker');
1256
1257                 if ($quit) {
1258                         return true;
1259                 }
1260
1261                 // We tell the daemon that a new job entry exists
1262                 if (Config::get('system', 'worker_daemon_mode', false)) {
1263                         // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
1264                         return true;
1265                 }
1266
1267                 // Now call the worker to execute the jobs that we just added to the queue
1268                 self::spawnWorker();
1269
1270                 return true;
1271         }
1272
1273         /**
1274          * Defers the current worker entry
1275          */
1276         public static function defer()
1277         {
1278                 if (empty(BaseObject::getApp()->queue)) {
1279                         return;
1280                 }
1281
1282                 $queue = BaseObject::getApp()->queue;
1283
1284                 $retrial = $queue['retrial'];
1285                 $id = $queue['id'];
1286                 $priority = $queue['priority'];
1287
1288                 if ($retrial > 14) {
1289                         Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
1290                         return;
1291                 }
1292
1293                 // Calculate the delay until the next trial
1294                 $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1295                 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1296
1297                 if (($priority < PRIORITY_MEDIUM) && ($retrial > 2)) {
1298                         $priority = PRIORITY_MEDIUM;
1299                 } elseif (($priority < PRIORITY_LOW) && ($retrial > 5)) {
1300                         $priority = PRIORITY_LOW;
1301                 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($retrial > 7)) {
1302                         $priority = PRIORITY_NEGLIGIBLE;
1303                 }
1304
1305                 Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next . ' - priority old/new: ' . $queue['priority'] . '/' . $priority, Logger::DEBUG);
1306
1307                 $stamp = (float)microtime(true);
1308                 $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1309                 DBA::update('workerqueue', $fields, ['id' => $id]);
1310                 self::$db_duration += (microtime(true) - $stamp);
1311                 self::$db_duration_write += (microtime(true) - $stamp);
1312         }
1313
1314         /**
1315          * Log active processes into the "process" table
1316          *
1317          * @brief Log active processes into the "process" table
1318          */
1319         public static function startProcess()
1320         {
1321                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
1322
1323                 $command = basename($trace[0]['file']);
1324
1325                 Process::deleteInactive();
1326
1327                 Process::insert($command);
1328         }
1329
1330         /**
1331          * Remove the active process from the "process" table
1332          *
1333          * @brief Remove the active process from the "process" table
1334          * @return bool
1335          * @throws \Exception
1336          */
1337         public static function endProcess()
1338         {
1339                 return Process::deleteByPid();
1340         }
1341
1342         /**
1343          * Set the flag if some job is waiting
1344          *
1345          * @brief Set the flag if some job is waiting
1346          * @param boolean $jobs Is there a waiting job?
1347          * @throws \Exception
1348          */
1349         public static function IPCSetJobState($jobs)
1350         {
1351                 $stamp = (float)microtime(true);
1352                 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1353                 self::$db_duration += (microtime(true) - $stamp);
1354                 self::$db_duration_write += (microtime(true) - $stamp);
1355         }
1356
1357         /**
1358          * Checks if some worker job waits to be executed
1359          *
1360          * @brief Checks if some worker job waits to be executed
1361          * @return bool
1362          * @throws \Exception
1363          */
1364         public static function IPCJobsExists()
1365         {
1366                 $stamp = (float)microtime(true);
1367                 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1368                 self::$db_duration += (microtime(true) - $stamp);
1369
1370                 // When we don't have a row, no job is running
1371                 if (!DBA::isResult($row)) {
1372                         return false;
1373                 }
1374
1375                 return (bool)$row['jobs'];
1376         }
1377 }