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