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