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