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