]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
Use "pcntl_fork" to fork processes
[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\App\Mode;
25 use Friendica\Core;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
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'];
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::notice('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                 DI::process()->start();
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::notice('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::notice('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::warning('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::notice('Active worker limit reached, quitting.');
173                         return false;
174                 }
175
176                 // Do we have too few memory?
177                 if (DI::process()->isMinMemoryReached()) {
178                         Logger::warning('Memory limit reached, quitting.');
179                         return false;
180                 }
181
182                 // Possibly there are too much database connections
183                 if (self::maxConnectionsReached()) {
184                         Logger::warning('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::warning('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::notice("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::warning("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::warning("Max connection reached for process", ['pid' => $mypid]);
301                         return false;
302                 }
303
304                 $argv = json_decode($queue['parameter'], true);
305                 if (!empty($queue['command'])) {
306                         array_unshift($argv, $queue['command']);
307                 }
308
309                 if (empty($argv)) {
310                         Logger::warning('Parameter is empty', ['queue' => $queue]);
311                         return false;
312                 }
313
314                 // Check for existance and validity of the include file
315                 $include = $argv[0];
316
317                 if (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
318                         // We constantly update the "executed" date every minute to avoid being killed too soon
319                         if (!isset(self::$last_update)) {
320                                 self::$last_update = strtotime($queue["executed"]);
321                         }
322
323                         $age = (time() - self::$last_update) / 60;
324                         self::$last_update = time();
325
326                         if ($age > 1) {
327                                 $stamp = (float)microtime(true);
328                                 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
329                                 self::$db_duration += (microtime(true) - $stamp);
330                                 self::$db_duration_write += (microtime(true) - $stamp);
331                         }
332
333                         array_shift($argv);
334
335                         self::execFunction($queue, $include, $argv, true);
336
337                         $stamp = (float)microtime(true);
338                         $condition = ["`id` = ? AND `next_try` < ?", $queue['id'], DateTimeFormat::utcNow()];
339                         if (DBA::update('workerqueue', ['done' => true], $condition)) {
340                                 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
341                         }
342                         self::$db_duration = (microtime(true) - $stamp);
343                         self::$db_duration_write += (microtime(true) - $stamp);
344
345                         return true;
346                 }
347
348                 // The script could be provided as full path or only with the function name
349                 if ($include == basename($include)) {
350                         $include = "include/".$include.".php";
351                 }
352
353                 if (!validate_include($include)) {
354                         Logger::warning("Include file is not valid", ['file' => $argv[0]]);
355                         $stamp = (float)microtime(true);
356                         DBA::delete('workerqueue', ['id' => $queue["id"]]);
357                         self::$db_duration = (microtime(true) - $stamp);
358                         self::$db_duration_write += (microtime(true) - $stamp);
359                         return true;
360                 }
361
362                 require_once $include;
363
364                 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
365
366                 if (function_exists($funcname)) {
367                         // We constantly update the "executed" date every minute to avoid being killed too soon
368                         if (!isset(self::$last_update)) {
369                                 self::$last_update = strtotime($queue["executed"]);
370                         }
371
372                         $age = (time() - self::$last_update) / 60;
373                         self::$last_update = time();
374
375                         if ($age > 1) {
376                                 $stamp = (float)microtime(true);
377                                 DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow()], ['pid' => $mypid, 'done' => false]);
378                                 self::$db_duration += (microtime(true) - $stamp);
379                                 self::$db_duration_write += (microtime(true) - $stamp);
380                         }
381
382                         self::execFunction($queue, $funcname, $argv, false);
383
384                         $stamp = (float)microtime(true);
385                         if (DBA::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
386                                 DI::config()->set('system', 'last_worker_execution', DateTimeFormat::utcNow());
387                         }
388                         self::$db_duration = (microtime(true) - $stamp);
389                         self::$db_duration_write += (microtime(true) - $stamp);
390                 } else {
391                         Logger::warning("Function does not exist", ['function' => $funcname]);
392                         $stamp = (float)microtime(true);
393                         DBA::delete('workerqueue', ['id' => $queue["id"]]);
394                         self::$db_duration = (microtime(true) - $stamp);
395                         self::$db_duration_write += (microtime(true) - $stamp);
396                 }
397
398                 return true;
399         }
400
401         /**
402          * Execute a function from the queue
403          *
404          * @param array   $queue       Workerqueue entry
405          * @param string  $funcname    name of the function
406          * @param array   $argv        Array of values to be passed to the function
407          * @param boolean $method_call boolean
408          * @return void
409          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410          */
411         private static function execFunction($queue, $funcname, $argv, $method_call)
412         {
413                 $a = DI::app();
414
415                 Logger::enableWorker($funcname);
416
417                 Logger::info("Process start.", ['priority' => $queue["priority"], 'id' => $queue["id"]]);
418
419                 $stamp = (float)microtime(true);
420
421                 // We use the callstack here to analyze the performance of executed worker entries.
422                 // For this reason the variables have to be initialized.
423                 DI::profiler()->reset();
424
425                 if (!in_array($queue['priority'], PRIORITIES)) {
426                         Logger::warning('Invalid priority', ['queue' => $queue, 'callstack' => System::callstack(20)]);
427                         $queue['priority'] = PRIORITY_MEDIUM;
428                 }
429
430                 $a->queue = $queue;
431
432                 $up_duration = microtime(true) - self::$up_start;
433
434                 // Reset global data to avoid interferences
435                 unset($_SESSION);
436
437                 // Set the workerLogger as new default logger
438                 if ($method_call) {
439                         call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
440                 } else {
441                         $funcname($argv, count($argv));
442                 }
443
444                 Logger::disableWorker();
445
446                 unset($a->queue);
447
448                 $duration = (microtime(true) - $stamp);
449
450                 /* With these values we can analyze how effective the worker is.
451                  * The database and rest time should be low since this is the unproductive time.
452                  * The execution time is the productive time.
453                  * By changing parameters like the maximum number of workers we can check the effectivness.
454                 */
455                 $dbtotal = round(self::$db_duration, 2);
456                 $dbread  = round(self::$db_duration - (self::$db_duration_count + self::$db_duration_write + self::$db_duration_stat), 2);
457                 $dbcount = round(self::$db_duration_count, 2);
458                 $dbstat  = round(self::$db_duration_stat, 2);
459                 $dbwrite = round(self::$db_duration_write, 2);
460                 $dblock  = round(self::$lock_duration, 2);
461                 $rest    = round(max(0, $up_duration - (self::$db_duration + self::$lock_duration)), 2);
462                 $exec    = round($duration, 2);
463
464                 Logger::info('Performance:', ['state' => self::$state, 'count' => $dbcount, 'stat' => $dbstat, 'write' => $dbwrite, 'lock' => $dblock, 'total' => $dbtotal, 'rest' => $rest, 'exec' => $exec]);
465
466                 self::$up_start = microtime(true);
467                 self::$db_duration = 0;
468                 self::$db_duration_count = 0;
469                 self::$db_duration_stat = 0;
470                 self::$db_duration_write = 0;
471                 self::$lock_duration = 0;
472
473                 if ($duration > 3600) {
474                         Logger::info('Longer than 1 hour.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
475                 } elseif ($duration > 600) {
476                         Logger::info('Longer than 10 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
477                 } elseif ($duration > 300) {
478                         Logger::info('Longer than 5 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
479                 } elseif ($duration > 120) {
480                         Logger::info('Longer than 2 minutes.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration/60, 3)]);
481                 }
482
483                 Logger::info('Process done.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'duration' => round($duration, 3)]);
484
485                 DI::profiler()->saveLog(DI::logger(), "ID " . $queue["id"] . ": " . $funcname);
486
487                 $cooldown = DI::config()->get("system", "worker_cooldown", 0);
488
489                 if ($cooldown > 0) {
490                         Logger::info('Cooldown.', ['priority' => $queue["priority"], 'id' => $queue["id"], 'cooldown' => $cooldown]);
491                         sleep($cooldown);
492                 }
493         }
494
495         /**
496          * Checks if the number of database connections has reached a critical limit.
497          *
498          * @return bool Are more than 3/4 of the maximum connections used?
499          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500          */
501         private static function maxConnectionsReached()
502         {
503                 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
504                 $max = DI::config()->get("system", "max_connections");
505
506                 // Fetch the percentage level where the worker will get active
507                 $maxlevel = DI::config()->get("system", "max_connections_level", 75);
508
509                 if ($max == 0) {
510                         // the maximum number of possible user connections can be a system variable
511                         $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
512                         if (DBA::isResult($r)) {
513                                 $max = $r["Value"];
514                         }
515                         // Or it can be granted. This overrides the system variable
516                         $stamp = (float)microtime(true);
517                         $r = DBA::p('SHOW GRANTS');
518                         self::$db_duration += (microtime(true) - $stamp);
519                         while ($grants = DBA::fetch($r)) {
520                                 $grant = array_pop($grants);
521                                 if (stristr($grant, "GRANT USAGE ON")) {
522                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
523                                                 $max = $match[1];
524                                         }
525                                 }
526                         }
527                         DBA::close($r);
528                 }
529
530                 // If $max is set we will use the processlist to determine the current number of connections
531                 // The processlist only shows entries of the current user
532                 if ($max != 0) {
533                         $stamp = (float)microtime(true);
534                         $r = DBA::p('SHOW PROCESSLIST');
535                         self::$db_duration += (microtime(true) - $stamp);
536                         $used = DBA::numRows($r);
537                         DBA::close($r);
538
539                         Logger::info("Connection usage (user values)", ['usage' => $used, 'max' => $max]);
540
541                         $level = ($used / $max) * 100;
542
543                         if ($level >= $maxlevel) {
544                                 Logger::warning("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
545                                 return true;
546                         }
547                 }
548
549                 // We will now check for the system values.
550                 // This limit could be reached although the user limits are fine.
551                 $r = DBA::fetchFirst("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
552                 if (!DBA::isResult($r)) {
553                         return false;
554                 }
555                 $max = intval($r["Value"]);
556                 if ($max == 0) {
557                         return false;
558                 }
559                 $r = DBA::fetchFirst("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
560                 if (!DBA::isResult($r)) {
561                         return false;
562                 }
563                 $used = intval($r["Value"]);
564                 if ($used == 0) {
565                         return false;
566                 }
567                 Logger::info("Connection usage (system values)", ['used' => $used, 'max' => $max]);
568
569                 $level = $used / $max * 100;
570
571                 if ($level < $maxlevel) {
572                         return false;
573                 }
574                 Logger::warning("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
575                 return true;
576         }
577
578         /**
579          * fix the queue entry if the worker process died
580          *
581          * @return void
582          * @throws \Exception
583          */
584         private static function killStaleWorkers()
585         {
586                 $stamp = (float)microtime(true);
587                 $entries = DBA::select(
588                         'workerqueue',
589                         ['id', 'pid', 'executed', 'priority', 'command', 'parameter'],
590                         ['NOT `done` AND `pid` != 0'],
591                         ['order' => ['priority', 'retrial', 'created']]
592                 );
593                 self::$db_duration += (microtime(true) - $stamp);
594
595                 while ($entry = DBA::fetch($entries)) {
596                         if (!posix_kill($entry["pid"], 0)) {
597                                 $stamp = (float)microtime(true);
598                                 DBA::update(
599                                         'workerqueue',
600                                         ['executed' => DBA::NULL_DATETIME, 'pid' => 0],
601                                         ['id' => $entry["id"]]
602                                 );
603                                 self::$db_duration += (microtime(true) - $stamp);
604                                 self::$db_duration_write += (microtime(true) - $stamp);
605                         } else {
606                                 // Kill long running processes
607                                 // Check if the priority is in a valid range
608                                 if (!in_array($entry["priority"], [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE])) {
609                                         $entry["priority"] = PRIORITY_MEDIUM;
610                                 }
611
612                                 // Define the maximum durations
613                                 $max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
614                                 $max_duration = $max_duration_defaults[$entry["priority"]];
615
616                                 $argv = json_decode($entry['parameter'], true);
617                                 if (!empty($entry['command'])) {
618                                         $command = $entry['command'];
619                                 } elseif (!empty($argv)) {
620                                         $command = array_shift($argv);
621                                 } else {
622                                         return;
623                                 }
624
625                                 $command = basename($command);
626
627                                 // How long is the process already running?
628                                 $duration = (time() - strtotime($entry["executed"])) / 60;
629                                 if ($duration > $max_duration) {
630                                         Logger::notice('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
631                                         posix_kill($entry["pid"], SIGTERM);
632
633                                         // We killed the stale process.
634                                         // To avoid a blocking situation we reschedule the process at the beginning of the queue.
635                                         // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
636                                         $new_priority = $entry["priority"];
637                                         if ($entry["priority"] == PRIORITY_HIGH) {
638                                                 $new_priority = PRIORITY_MEDIUM;
639                                         } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
640                                                 $new_priority = PRIORITY_LOW;
641                                         } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
642                                                 $new_priority = PRIORITY_NEGLIGIBLE;
643                                         }
644                                         $stamp = (float)microtime(true);
645                                         DBA::update(
646                                                 'workerqueue',
647                                                 ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
648                                                 ['id' => $entry["id"]]
649                                         );
650                                         self::$db_duration += (microtime(true) - $stamp);
651                                         self::$db_duration_write += (microtime(true) - $stamp);
652                                 } else {
653                                         Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
654                                 }
655                         }
656                 }
657                 DBA::close($entries);
658         }
659
660         /**
661          * Checks if the number of active workers exceeds the given limits
662          *
663          * @return bool Are there too much workers running?
664          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
665          */
666         private static function tooMuchWorkers()
667         {
668                 $queues = DI::config()->get("system", "worker_queues", 10);
669
670                 $maxqueues = $queues;
671
672                 $active = self::activeWorkers();
673
674                 // Decrease the number of workers at higher load
675                 $load = System::currentLoad();
676                 if ($load) {
677                         $maxsysload = intval(DI::config()->get("system", "maxloadavg", 20));
678
679                         /* Default exponent 3 causes queues to rapidly decrease as load increases.
680                          * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
681                          * For some environments, this rapid decrease is not needed.
682                          * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
683                          */
684                         $exponent = intval(DI::config()->get('system', 'worker_load_exponent', 3));
685                         $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
686                         $queues = intval(ceil($slope * $maxqueues));
687
688                         $processlist = '';
689
690                         if (DI::config()->get('system', 'worker_jpm')) {
691                                 $intervals = explode(',', DI::config()->get('system', 'worker_jpm_range'));
692                                 $jobs_per_minute = [];
693                                 foreach ($intervals as $interval) {
694                                         if ($interval == 0) {
695                                                 continue;
696                                         } else {
697                                                 $interval = (int)$interval;
698                                         }
699
700                                         $stamp = (float)microtime(true);
701                                         $jobs = DBA::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ? MINUTE", $interval);
702                                         self::$db_duration += (microtime(true) - $stamp);
703                                         self::$db_duration_stat += (microtime(true) - $stamp);
704                                         if ($job = DBA::fetch($jobs)) {
705                                                 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
706                                         }
707                                         DBA::close($jobs);
708                                 }
709                                 $processlist = ' - jpm: '.implode('/', $jobs_per_minute);
710                         }
711
712                         // Create a list of queue entries grouped by their priority
713                         $listitem = [0 => ''];
714
715                         $idle_workers = $active;
716
717                         $deferred = self::deferredEntries();
718
719                         if (DI::config()->get('system', 'worker_debug')) {
720                                 $waiting_processes = 0;
721                                 // Now adding all processes with workerqueue entries
722                                 $stamp = (float)microtime(true);
723                                 $jobs = DBA::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
724                                 self::$db_duration += (microtime(true) - $stamp);
725                                 self::$db_duration_stat += (microtime(true) - $stamp);
726                                 while ($entry = DBA::fetch($jobs)) {
727                                         $stamp = (float)microtime(true);
728                                         $processes = DBA::p("SELECT COUNT(*) AS `running` FROM `workerqueue-view` WHERE `priority` = ?", $entry["priority"]);
729                                         self::$db_duration += (microtime(true) - $stamp);
730                                         self::$db_duration_stat += (microtime(true) - $stamp);
731                                         if ($process = DBA::fetch($processes)) {
732                                                 $idle_workers -= $process["running"];
733                                                 $waiting_processes += $entry["entries"];
734                                                 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
735                                         }
736                                         DBA::close($processes);
737                                 }
738                                 DBA::close($jobs);
739                         } else {
740                                 $waiting_processes =  self::totalEntries();
741                                 $stamp = (float)microtime(true);
742                                 $jobs = DBA::p("SELECT COUNT(*) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority` ORDER BY `priority`");
743                                 self::$db_duration += (microtime(true) - $stamp);
744                                 self::$db_duration_stat += (microtime(true) - $stamp);
745
746                                 while ($entry = DBA::fetch($jobs)) {
747                                         $idle_workers -= $entry["running"];
748                                         $listitem[$entry["priority"]] = $entry["priority"].":".$entry["running"];
749                                 }
750                                 DBA::close($jobs);
751                         }
752
753                         $waiting_processes -= $deferred;
754
755                         $listitem[0] = "0:" . max(0, $idle_workers);
756
757                         $processlist .= ' ('.implode(', ', $listitem).')';
758
759                         if (DI::config()->get("system", "worker_fastlane", false) && ($queues > 0) && ($active >= $queues) && self::entriesExists()) {
760                                 $top_priority = self::highestPriority();
761                                 $high_running = self::processWithPriorityActive($top_priority);
762
763                                 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
764                                         Logger::info("Jobs with a higher priority are waiting but none is executed. Open a fastlane.", ['priority' => $top_priority]);
765                                         $queues = $active + 1;
766                                 }
767                         }
768
769                         Logger::notice("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $waiting_processes . $processlist . " - maximum: " . $queues . "/" . $maxqueues);
770
771                         // Are there fewer workers running as possible? Then fork a new one.
772                         if (!DI::config()->get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && self::entriesExists()) {
773                                 Logger::info("There are fewer workers as possible, fork a new worker.", ['active' => $active, 'queues' => $queues]);
774                                 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
775                                         self::IPCSetJobState(true);
776                                 } else {
777                                         self::spawnWorker();
778                                 }
779                         }
780                 }
781
782                 // if there are too much worker, we don't spawn a new one.
783                 if (DI::config()->get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
784                         self::IPCSetJobState(false);
785                 }
786
787                 return $active > $queues;
788         }
789
790         /**
791          * Returns the number of active worker processes
792          *
793          * @return integer Number of active worker processes
794          * @throws \Exception
795          */
796         private static function activeWorkers()
797         {
798                 $stamp = (float)microtime(true);
799                 $count = DBA::count('process', ['command' => 'Worker.php']);
800                 self::$db_duration += (microtime(true) - $stamp);
801                 self::$db_duration_count += (microtime(true) - $stamp);
802                 return $count;
803         }
804
805         /**
806          * Returns the number of active worker processes
807          *
808          * @return array List of worker process ids
809          * @throws \Exception
810          */
811         private static function getWorkerPIDList()
812         {
813                 $ids = [];
814                 $stamp = (float)microtime(true);
815
816                 $queues = DBA::p("SELECT `process`.`pid`, COUNT(`workerqueue`.`pid`) AS `entries` FROM `process`
817                         LEFT JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `workerqueue`.`done` 
818                         GROUP BY `process`.`pid`");
819                 while ($queue = DBA::fetch($queues)) {
820                         $ids[$queue['pid']] = $queue['entries'];
821                 }
822                 DBA::close($queues);
823
824                 self::$db_duration += (microtime(true) - $stamp);
825                 self::$db_duration_count += (microtime(true) - $stamp);
826                 return $ids;
827         }
828
829         /**
830          * Returns waiting jobs for the current process id
831          *
832          * @return array waiting workerqueue jobs
833          * @throws \Exception
834          */
835         private static function getWaitingJobForPID()
836         {
837                 $stamp = (float)microtime(true);
838                 $r = DBA::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
839                 self::$db_duration += (microtime(true) - $stamp);
840                 if (DBA::isResult($r)) {
841                         return DBA::toArray($r);
842                 }
843                 DBA::close($r);
844
845                 return false;
846         }
847
848         /**
849          * Returns the next jobs that should be executed
850          * @param int $limit
851          * @return array array with next jobs
852          * @throws \Exception
853          */
854         private static function nextProcess(int $limit)
855         {
856                 $priority = self::nextPriority();
857                 if (empty($priority)) {
858                         Logger::info('No tasks found');
859                         return [];
860                 }
861
862                 $ids = [];
863                 $stamp = (float)microtime(true);
864                 $condition = ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()];
865                 $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['retrial', 'created']]);
866                 self::$db_duration += (microtime(true) - $stamp);
867                 while ($task = DBA::fetch($tasks)) {
868                         $ids[] = $task['id'];
869                         // Only continue that loop while we are storing commands that can be processed quickly
870                         if (!empty($task['command'])) {
871                                 $command = $task['command'];
872                         } else {
873                                 $command = json_decode($task['parameter'])[0];
874                         }
875
876                         if (!in_array($command, self::FAST_COMMANDS)) {
877                                 break;
878                         }
879                 }
880                 DBA::close($tasks);
881
882                 Logger::info('Found:', ['priority' => $priority, 'id' => $ids]);
883                 return $ids;
884         }
885
886         /**
887          * Returns the priority of the next workerqueue job
888          *
889          * @return string priority
890          * @throws \Exception
891          */
892         private static function nextPriority()
893         {
894                 $waiting = [];
895                 $priorities = [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE];
896                 foreach ($priorities as $priority) {
897                         $stamp = (float)microtime(true);
898                         if (DBA::exists('workerqueue', ["`priority` = ? AND `pid` = 0 AND NOT `done` AND `next_try` < ?", $priority, DateTimeFormat::utcNow()])) {
899                                 $waiting[$priority] = true;
900                         }
901                         self::$db_duration += (microtime(true) - $stamp);
902                 }
903
904                 if (!empty($waiting[PRIORITY_CRITICAL])) {
905                         return PRIORITY_CRITICAL;
906                 }
907
908                 $running = [];
909                 $running_total = 0;
910                 $stamp = (float)microtime(true);
911                 $processes = DBA::p("SELECT COUNT(DISTINCT(`pid`)) AS `running`, `priority` FROM `workerqueue-view` GROUP BY `priority`");
912                 self::$db_duration += (microtime(true) - $stamp);
913                 while ($process = DBA::fetch($processes)) {
914                         $running[$process['priority']] = $process['running'];
915                         $running_total += $process['running'];
916                 }
917                 DBA::close($processes);
918
919                 foreach ($priorities as $priority) {
920                         if (!empty($waiting[$priority]) && empty($running[$priority])) {
921                                 Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
922                                 return $priority;
923                         }
924                 }
925
926                 $active = max(self::activeWorkers(), $running_total);
927                 $priorities = max(count($waiting), count($running));
928                 $exponent = 2;
929
930                 $total = 0;
931                 for ($i = 1; $i <= $priorities; ++$i) {
932                         $total += pow($i, $exponent);
933                 }
934
935                 $limit = [];
936                 for ($i = 1; $i <= $priorities; ++$i) {
937                         $limit[$priorities - $i] = max(1, round($active * (pow($i, $exponent) / $total)));
938                 }
939
940                 $i = 0;
941                 foreach ($running as $priority => $workers) {
942                         if ($workers < $limit[$i++]) {
943                                 Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
944                                 return $priority;
945                         }
946                 }
947
948                 if (!empty($waiting)) {
949                         $priority = array_keys($waiting)[0];
950                         Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
951                         return $priority;
952                 }
953
954                 return false;
955         }
956
957         /**
958          * Find and claim the next worker process for us
959          *
960          * @return boolean Have we found something?
961          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
962          */
963         private static function findWorkerProcesses()
964         {
965                 $fetch_limit = DI::config()->get('system', 'worker_fetch_limit', 1);
966
967                 if (DI::config()->get('system', 'worker_multiple_fetch')) {
968                         $pids = [];
969                         foreach (self::getWorkerPIDList() as $pid => $count) {
970                                 if ($count <= $fetch_limit) {
971                                         $pids[] = $pid;
972                                 }
973                         }
974                         if (empty($pids)) {
975                                 return;
976                         }
977                         $limit = $fetch_limit * count($pids);
978                 } else {
979                         $pids = [getmypid()];
980                         $limit = $fetch_limit;
981                 }
982
983                 $ids = self::nextProcess($limit);
984                 $limit -= count($ids);
985
986                 // If there is not enough results we check without priority limit
987                 if ($limit > 0) {
988                         $stamp = (float)microtime(true);
989                         $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
990                         $tasks = DBA::select('workerqueue', ['id', 'command', 'parameter'], $condition, ['limit' => $limit, 'order' => ['priority', 'retrial', 'created']]);
991                         self::$db_duration += (microtime(true) - $stamp);
992
993                         while ($task = DBA::fetch($tasks)) {
994                                 $ids[] = $task['id'];
995                                 // Only continue that loop while we are storing commands that can be processed quickly
996                                 if (!empty($task['command'])) {
997                                         $command = $task['command'];
998                                 } else {
999                                         $command = json_decode($task['parameter'])[0];
1000                                 }
1001                                 if (!in_array($command, self::FAST_COMMANDS)) {
1002                                         break;
1003                                 }
1004                         }
1005                         DBA::close($tasks);
1006                 }
1007
1008                 if (empty($ids)) {
1009                         return;
1010                 }
1011
1012                 // Assign the task ids to the workers
1013                 $worker = [];
1014                 foreach (array_unique($ids) as $id) {
1015                         $pid = next($pids);
1016                         if (!$pid) {
1017                                 $pid = reset($pids);
1018                         }
1019                         $worker[$pid][] = $id;
1020                 }
1021
1022                 $stamp = (float)microtime(true);
1023                 foreach ($worker as $worker_pid => $worker_ids) {
1024                         Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
1025                         DBA::update('workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
1026                                 ['id' => $worker_ids, 'done' => false, 'pid' => 0]);
1027                 }
1028                 self::$db_duration += (microtime(true) - $stamp);
1029                 self::$db_duration_write += (microtime(true) - $stamp);
1030         }
1031
1032         /**
1033          * Returns the next worker process
1034          *
1035          * @return array worker processes
1036          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1037          */
1038         public static function workerProcess()
1039         {
1040                 // There can already be jobs for us in the queue.
1041                 $waiting = self::getWaitingJobForPID();
1042                 if (!empty($waiting)) {
1043                         return $waiting;
1044                 }
1045
1046                 $stamp = (float)microtime(true);
1047                 if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
1048                         return false;
1049                 }
1050                 self::$lock_duration += (microtime(true) - $stamp);
1051
1052                 self::findWorkerProcesses();
1053
1054                 DI::lock()->release(self::LOCK_PROCESS);
1055
1056                 return self::getWaitingJobForPID();
1057         }
1058
1059         /**
1060          * Removes a workerqueue entry from the current process
1061          *
1062          * @return void
1063          * @throws \Exception
1064          */
1065         public static function unclaimProcess()
1066         {
1067                 $mypid = getmypid();
1068
1069                 $stamp = (float)microtime(true);
1070                 DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'pid' => 0], ['pid' => $mypid, 'done' => false]);
1071                 self::$db_duration += (microtime(true) - $stamp);
1072                 self::$db_duration_write += (microtime(true) - $stamp);
1073         }
1074
1075         /**
1076          * Call the front end worker
1077          *
1078          * @return void
1079          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080          */
1081         public static function callWorker()
1082         {
1083                 if (!DI::config()->get("system", "frontend_worker")) {
1084                         return;
1085                 }
1086
1087                 $url = DI::baseUrl() . '/worker';
1088                 DI::httpRequest()->fetch($url, 1);
1089         }
1090
1091         /**
1092          * Call the front end worker if there aren't any active
1093          *
1094          * @return void
1095          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096          */
1097         public static function executeIfIdle()
1098         {
1099                 self::checkDaemonState();
1100
1101                 if (!DI::config()->get("system", "frontend_worker")) {
1102                         return;
1103                 }
1104
1105                 // Do we have "proc_open"? Then we can fork the worker
1106                 if (function_exists("proc_open")) {
1107                         // When was the last time that we called the worker?
1108                         // Less than one minute? Then we quit
1109                         if ((time() - DI::config()->get("system", "worker_started")) < 60) {
1110                                 return;
1111                         }
1112
1113                         DI::config()->set("system", "worker_started", time());
1114
1115                         // Do we have enough running workers? Then we quit here.
1116                         if (self::tooMuchWorkers()) {
1117                                 // Cleaning dead processes
1118                                 self::killStaleWorkers();
1119                                 DI::modelProcess()->deleteInactive();
1120
1121                                 return;
1122                         }
1123
1124                         self::runCron();
1125
1126                         Logger::info('Call worker');
1127                         self::spawnWorker();
1128                         return;
1129                 }
1130
1131                 // We cannot execute background processes.
1132                 // We now run the processes from the frontend.
1133                 // This won't work with long running processes.
1134                 self::runCron();
1135
1136                 self::clearProcesses();
1137
1138                 $workers = self::activeWorkers();
1139
1140                 if ($workers == 0) {
1141                         self::callWorker();
1142                 }
1143         }
1144
1145         /**
1146          * Removes long running worker processes
1147          *
1148          * @return void
1149          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1150          */
1151         public static function clearProcesses()
1152         {
1153                 $timeout = DI::config()->get("system", "frontend_worker_timeout", 10);
1154
1155                 /// @todo We should clean up the corresponding workerqueue entries as well
1156                 $stamp = (float)microtime(true);
1157                 $condition = ["`created` < ? AND `command` = 'worker.php'",
1158                                 DateTimeFormat::utc("now - ".$timeout." minutes")];
1159                 DBA::delete('process', $condition);
1160                 self::$db_duration = (microtime(true) - $stamp);
1161                 self::$db_duration_write += (microtime(true) - $stamp);
1162         }
1163
1164         /**
1165          * Runs the cron processes
1166          *
1167          * @return void
1168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1169          */
1170         private static function runCron()
1171         {
1172                 Logger::info('Add cron entries');
1173
1174                 // Check for spooled items
1175                 self::add(['priority' => PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
1176
1177                 // Run the cron job that calls all other jobs
1178                 self::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'Cron');
1179
1180                 // Cleaning dead processes
1181                 self::killStaleWorkers();
1182         }
1183
1184         /**
1185          * Fork a child process
1186          *
1187          * @param boolean $do_cron
1188          * @return void
1189          */
1190         private static function forkProcess(bool $do_cron)
1191         {
1192                 // Children inherit their parent's database connection.
1193                 // To avoid problems we disconnect and connect both parent and child
1194                 DBA::disconnect();
1195                 $pid = pcntl_fork();
1196                 if ($pid == -1) {
1197                         DBA::connect();
1198                         Logger::warning('Could not spawn worker');
1199                         return;
1200                 } elseif ($pid) {
1201                         // The parent process continues here
1202                         DBA::connect();
1203                         Logger::info('Spawned new worker', ['cron' => $do_cron, 'pid' => $pid]);
1204                         return;
1205                 }
1206         
1207                 // We now are in the new worker
1208                 DBA::connect();
1209                 Logger::info('Worker spawned', ['cron' => $do_cron, 'pid' => getmypid()]);
1210
1211                 DI::process()->start();
1212
1213                 self::processQueue($do_cron);
1214
1215                 self::unclaimProcess();
1216
1217                 DI::process()->end();
1218                 Logger::info('Worker ended', ['cron' => $do_cron, 'pid' => getmypid()]);
1219                 exit();
1220         }
1221
1222         /**
1223          * Spawns a new worker
1224          *
1225          * @param bool $do_cron
1226          * @return void
1227          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228          */
1229         public static function spawnWorker($do_cron = false)
1230         {
1231                 // Worker and daemon are started from the command line.
1232                 // This means that this is executed by a PHP interpreter without runtime limitations
1233                 if (in_array(DI::mode()->getExecutor(), [Mode::DAEMON, Mode::WORKER])) {
1234                         self::forkProcess($do_cron);
1235                 } else {
1236                         $process = new Core\Process(DI::logger(), DI::mode(), DI::config(),
1237                                 DI::modelProcess(), DI::app()->getBasePath(), getmypid());
1238                         $process->run('bin/worker.php', ['no_cron' => !$do_cron]);
1239                 }
1240
1241                 // after spawning we have to remove the flag.
1242                 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1243                         self::IPCSetJobState(false);
1244                 }
1245         }
1246
1247         /**
1248          * Adds tasks to the worker queue
1249          *
1250          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
1251          *
1252          * next args are passed as $cmd command line
1253          * or: Worker::add(PRIORITY_HIGH, "Notifier", Delivery::DELETION, $drop_id);
1254          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "Delivery", $post_id);
1255          *
1256          * @return boolean "false" if worker queue entry already existed or there had been an error
1257          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1258          * @note $cmd and string args are surrounded with ""
1259          *
1260          * @hooks 'proc_run'
1261          *    array $arr
1262          *
1263          */
1264         public static function add($cmd)
1265         {
1266                 $args = func_get_args();
1267
1268                 if (!count($args)) {
1269                         return false;
1270                 }
1271
1272                 $arr = ['args' => $args, 'run_cmd' => true];
1273
1274                 Hook::callAll("proc_run", $arr);
1275                 if (!$arr['run_cmd'] || !count($args)) {
1276                         return true;
1277                 }
1278
1279                 $priority = PRIORITY_MEDIUM;
1280                 // Don't fork from frontend tasks by default
1281                 $dont_fork = DI::config()->get("system", "worker_dont_fork", false) || !DI::mode()->isBackend();
1282                 $created = DateTimeFormat::utcNow();
1283                 $delayed = DBA::NULL_DATETIME;
1284                 $force_priority = false;
1285
1286                 $run_parameter = array_shift($args);
1287
1288                 if (is_int($run_parameter)) {
1289                         $priority = $run_parameter;
1290                 } elseif (is_array($run_parameter)) {
1291                         if (isset($run_parameter['delayed'])) {
1292                                 $delayed = $run_parameter['delayed'];
1293                         }
1294                         if (isset($run_parameter['priority'])) {
1295                                 $priority = $run_parameter['priority'];
1296                         }
1297                         if (isset($run_parameter['created'])) {
1298                                 $created = $run_parameter['created'];
1299                         }
1300                         if (isset($run_parameter['dont_fork'])) {
1301                                 $dont_fork = $run_parameter['dont_fork'];
1302                         }
1303                         if (isset($run_parameter['force_priority'])) {
1304                                 $force_priority = $run_parameter['force_priority'];
1305                         }
1306                 }
1307
1308                 $command = array_shift($args);
1309                 $parameters = json_encode($args);
1310                 $found = DBA::exists('workerqueue', ['command' => $command, 'parameter' => $parameters, 'done' => false]);
1311                 $added = false;
1312
1313                 if (!in_array($priority, PRIORITIES)) {
1314                         Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command, 'callstack' => System::callstack(20)]);
1315                         $priority = PRIORITY_MEDIUM;
1316                 }
1317
1318                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1319                 if (DBA::errorNo() != 0) {
1320                         return false;
1321                 }
1322
1323                 if (!$found) {
1324                         $added = DBA::insert('workerqueue', ['command' => $command, 'parameter' => $parameters, 'created' => $created,
1325                                 'priority' => $priority, 'next_try' => $delayed]);
1326                         if (!$added) {
1327                                 return false;
1328                         }
1329                 } elseif ($force_priority) {
1330                         DBA::update('workerqueue', ['priority' => $priority], ['command' => $command, 'parameter' => $parameters, 'done' => false, 'pid' => 0]);
1331                 }
1332
1333                 // Set the IPC flag to ensure an immediate process execution via daemon
1334                 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1335                         self::IPCSetJobState(true);
1336                 }
1337
1338                 self::checkDaemonState();
1339
1340                 // Should we quit and wait for the worker to be called as a cronjob?
1341                 if ($dont_fork) {
1342                         return $added;
1343                 }
1344
1345                 // If there is a lock then we don't have to check for too much worker
1346                 if (!DI::lock()->acquire(self::LOCK_WORKER, 0)) {
1347                         return $added;
1348                 }
1349
1350                 // If there are already enough workers running, don't fork another one
1351                 $quit = self::tooMuchWorkers();
1352                 DI::lock()->release(self::LOCK_WORKER);
1353
1354                 if ($quit) {
1355                         return $added;
1356                 }
1357
1358                 // Quit on daemon mode
1359                 if (DI::config()->get('system', 'worker_daemon_mode', false)) {
1360                         return $added;
1361                 }
1362
1363                 // Now call the worker to execute the jobs that we just added to the queue
1364                 self::spawnWorker();
1365
1366                 return $added;
1367         }
1368
1369         public static function countWorkersByCommand(string $command)
1370         {
1371                 return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
1372         }
1373
1374         /**
1375          * Returns the next retrial level for worker jobs.
1376          * This function will skip levels when jobs are older.
1377          *
1378          * @param array $queue Worker queue entry
1379          * @param integer $max_level maximum retrial level
1380          * @return integer the next retrial level value
1381          */
1382         private static function getNextRetrial($queue, $max_level)
1383         {
1384                 $created = strtotime($queue['created']);
1385                 $retrial_time = time() - $created;
1386
1387                 $new_retrial = $queue['retrial'] + 1;
1388                 $total = 0;
1389                 for ($retrial = 0; $retrial <= $max_level + 1; ++$retrial) {
1390                         $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
1391                         $total += $delay;
1392                         if (($total < $retrial_time) && ($retrial > $queue['retrial'])) {
1393                                 $new_retrial = $retrial;
1394                         }
1395                 }
1396                 Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
1397                 return $new_retrial;
1398         }
1399
1400         /**
1401          * Defers the current worker entry
1402          *
1403          * @return boolean had the entry been deferred?
1404          */
1405         public static function defer()
1406         {
1407                 if (empty(DI::app()->queue)) {
1408                         return false;
1409                 }
1410
1411                 $queue = DI::app()->queue;
1412
1413                 $retrial = $queue['retrial'];
1414                 $id = $queue['id'];
1415                 $priority = $queue['priority'];
1416
1417                 $max_level = DI::config()->get('system', 'worker_defer_limit');
1418
1419                 $new_retrial = self::getNextRetrial($queue, $max_level);
1420
1421                 if ($new_retrial > $max_level) {
1422                         Logger::notice('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]);
1423                         return false;
1424                 }
1425
1426                 // Calculate the delay until the next trial
1427                 $delay = (($new_retrial + 2) ** 4) + (rand(1, 30) * ($new_retrial));
1428                 $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
1429
1430                 if (($priority < PRIORITY_MEDIUM) && ($new_retrial > 3)) {
1431                         $priority = PRIORITY_MEDIUM;
1432                 } elseif (($priority < PRIORITY_LOW) && ($new_retrial > 6)) {
1433                         $priority = PRIORITY_LOW;
1434                 } elseif (($priority < PRIORITY_NEGLIGIBLE) && ($new_retrial > 8)) {
1435                         $priority = PRIORITY_NEGLIGIBLE;
1436                 }
1437
1438                 Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
1439
1440                 $stamp = (float)microtime(true);
1441                 $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
1442                 DBA::update('workerqueue', $fields, ['id' => $id]);
1443                 self::$db_duration += (microtime(true) - $stamp);
1444                 self::$db_duration_write += (microtime(true) - $stamp);
1445
1446                 return true;
1447         }
1448
1449         /**
1450          * Set the flag if some job is waiting
1451          *
1452          * @param boolean $jobs Is there a waiting job?
1453          * @throws \Exception
1454          */
1455         public static function IPCSetJobState($jobs)
1456         {
1457                 $stamp = (float)microtime(true);
1458                 DBA::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
1459                 self::$db_duration += (microtime(true) - $stamp);
1460                 self::$db_duration_write += (microtime(true) - $stamp);
1461         }
1462
1463         /**
1464          * Checks if some worker job waits to be executed
1465          *
1466          * @return bool
1467          * @throws \Exception
1468          */
1469         public static function IPCJobsExists()
1470         {
1471                 $stamp = (float)microtime(true);
1472                 $row = DBA::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
1473                 self::$db_duration += (microtime(true) - $stamp);
1474
1475                 // When we don't have a row, no job is running
1476                 if (!DBA::isResult($row)) {
1477                         return false;
1478                 }
1479
1480                 return (bool)$row['jobs'];
1481         }
1482
1483         /**
1484          * Test if the daemon is running. If not, it will be started
1485          *
1486          * @return void
1487          */
1488         private static function checkDaemonState()
1489         {
1490                 if (!DI::config()->get('system', 'daemon_watchdog', false)) {
1491                         return;
1492                 }
1493
1494                 if (!DI::mode()->isNormal()) {
1495                         return;
1496                 }
1497
1498                 // Check every minute if the daemon is running
1499                 if (DI::config()->get('system', 'last_daemon_check', 0) + 60 > time()) {
1500                         return;
1501                 }
1502
1503                 DI::config()->set('system', 'last_daemon_check', time());
1504
1505                 $pidfile = DI::config()->get('system', 'pidfile');
1506                 if (empty($pidfile)) {
1507                         // No pid file, no daemon
1508                         return;
1509                 }
1510
1511                 if (!is_readable($pidfile)) {
1512                         // No pid file. We assume that the daemon had been intentionally stopped.
1513                         return;
1514                 }
1515
1516                 $pid = intval(file_get_contents($pidfile));
1517                 if (posix_kill($pid, 0)) {
1518                         Logger::info('Daemon process is running', ['pid' => $pid]);
1519                         return;
1520                 }
1521
1522                 Logger::warning('Daemon process is not running', ['pid' => $pid]);
1523
1524                 self::spawnDaemon();
1525         }
1526
1527         /**
1528          * Spawn a new daemon process
1529          *
1530          * @return void
1531          */
1532         private static function spawnDaemon()
1533         {
1534                 Logger::notice('Starting new daemon process');
1535                 $command = 'bin/daemon.php';
1536                 $a = DI::app();
1537                 $process = new Core\Process(DI::logger(), DI::mode(), DI::config(), DI::modelProcess(), $a->getBasePath(), getmypid());
1538                 $process->run($command, ['start']);
1539                 Logger::notice('New daemon process started');
1540         }
1541
1542         /**
1543          * Check if the system is inside the defined maintenance window
1544          *
1545          * @return boolean
1546          */
1547         public static function isInMaintenanceWindow(bool $check_last_execution = false)
1548         {
1549                 // Calculate the seconds of the start end end of the maintenance window
1550                 $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
1551                 $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
1552
1553                 Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1554
1555                 if ($check_last_execution) {
1556                         // Calculate the window duration
1557                         $duration = max($start, $end) - min($start, $end);
1558
1559                         // Quit when the last cron execution had been after the previous window
1560                         $last_cron = DI::config()->get('system', 'last_cron_daily');
1561                         if ($last_cron + $duration > time()) {
1562                                 Logger::info('The Daily cron had been executed recently', ['last' => date(DateTimeFormat::MYSQL, $last_cron), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1563                                 return false;
1564                         }
1565                 }
1566
1567                 $current = time() % 86400;
1568
1569                 if ($start < $end) {
1570                         // Execute if we are inside the window
1571                         $execute = ($current >= $start) && ($current <= $end);
1572                 } else {
1573                         // Don't execute if we are outside the window
1574                         $execute = !(($current > $end) && ($current < $start));
1575                 }
1576
1577                 if ($execute) {
1578                         Logger::info('We are inside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1579                 } else {
1580                         Logger::info('We are outside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
1581                 }
1582                 
1583                 return $execute;
1584         }
1585 }