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