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