]> git.mxchange.org Git - friendica.git/blob - src/Core/System.php
Deactivating isMinMemoryReached()
[friendica.git] / src / Core / System.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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 Exception;
25 use Friendica\App;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
27 use Friendica\DI;
28 use Friendica\Network\HTTPException\FoundException;
29 use Friendica\Network\HTTPException\MovedPermanentlyException;
30 use Friendica\Network\HTTPException\TemporaryRedirectException;
31 use Friendica\Util\BasePath;
32 use Friendica\Util\XML;
33 use Psr\Log\LoggerInterface;
34
35 /**
36  * Contains the class with system relevant stuff
37  */
38 class System
39 {
40         /**
41          * @var LoggerInterface
42          */
43         private $logger;
44
45         /**
46          * @var IManageConfigValues
47          */
48         private $config;
49
50         /**
51          * @var string
52          */
53         private $basePath;
54
55         public function __construct(LoggerInterface $logger, IManageConfigValues $config, string $basepath)
56         {
57                 $this->logger   = $logger;
58                 $this->config   = $config;
59                 $this->basePath = $basepath;
60         }
61
62         /**
63          * Checks if the maximum number of database processes is reached
64          *
65          * @return bool Is the limit reached?
66          */
67         public function isMaxProcessesReached(): bool
68         {
69                 // Deactivated, needs more investigating if this check really makes sense
70                 return false;
71
72                 /*
73                  * Commented out to suppress static analyzer issues
74                  *
75                 if ($this->mode->isBackend()) {
76                         $process = 'backend';
77                         $max_processes = $this->config->get('system', 'max_processes_backend');
78                         if (intval($max_processes) == 0) {
79                                 $max_processes = 5;
80                         }
81                 } else {
82                         $process = 'frontend';
83                         $max_processes = $this->config->get('system', 'max_processes_frontend');
84                         if (intval($max_processes) == 0) {
85                                 $max_processes = 20;
86                         }
87                 }
88
89                 $processlist = DBA::processlist();
90                 if ($processlist['list'] != '') {
91                         $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
92
93                         if ($processlist['amount'] > $max_processes) {
94                                 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
95                                 return true;
96                         }
97                 }
98                 return false;
99                  */
100         }
101
102         /**
103          * Checks if the minimal memory is reached
104          *
105          * @return bool Is the memory limit reached?
106          */
107         public function isMinMemoryReached(): bool
108         {
109                 // Deactivated, needs more investigating if this check really makes sense
110                 return false;
111
112                 /*
113                  * Commented out to suppress static analyzer issues
114                  *
115                 $min_memory = $this->config->get('system', 'min_memory', 0);
116                 if ($min_memory == 0) {
117                         return false;
118                 }
119
120                 if (!is_readable('/proc/meminfo')) {
121                         return false;
122                 }
123
124                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
125
126                 $meminfo = [];
127                 foreach ($memdata as $line) {
128                         $data = explode(':', $line);
129                         if (count($data) != 2) {
130                                 continue;
131                         }
132                         [$key, $val]     = $data;
133                         $meminfo[$key]   = (int)trim(str_replace('kB', '', $val));
134                         $meminfo[$key]   = (int)($meminfo[$key] / 1024);
135                 }
136
137                 if (!isset($meminfo['MemFree'])) {
138                         return false;
139                 }
140
141                 $free = $meminfo['MemFree'];
142
143                 $reached = ($free < $min_memory);
144
145                 if ($reached) {
146                         $this->logger->warning('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
147                 }
148
149                 return $reached;
150                  */
151         }
152
153         /**
154          * Checks if the maximum load is reached
155          *
156          * @return bool Is the load reached?
157          */
158         public function isMaxLoadReached(): bool
159         {
160                 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
161                 if ($maxsysload < 1) {
162                         $maxsysload = 50;
163                 }
164
165                 $load = System::currentLoad();
166                 if ($load) {
167                         if (intval($load) > $maxsysload) {
168                                 $this->logger->warning('system load for process too high.', ['load' => $load, 'process' => 'backend', 'maxsysload' => $maxsysload]);
169                                 return true;
170                         }
171                 }
172                 return false;
173         }
174
175         /**
176          * Executes a child process with 'proc_open'
177          *
178          * @param string $command The command to execute
179          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
180          */
181         public function run(string $command, array $args)
182         {
183                 if (!function_exists('proc_open')) {
184                         $this->logger->warning('"proc_open" not available - quitting');
185                         return;
186                 }
187
188                 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
189
190                 foreach ($args as $key => $value) {
191                         if (!is_null($value) && is_bool($value) && !$value) {
192                                 continue;
193                         }
194
195                         $cmdline .= ' --' . $key;
196                         if (!is_null($value) && !is_bool($value)) {
197                                 $cmdline .= ' ' . $value;
198                         }
199                 }
200
201                 if ($this->isMinMemoryReached()) {
202                         $this->logger->warning('Memory limit reached - quitting');
203                         return;
204                 }
205
206                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
207                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->basePath);
208                 } else {
209                         $resource = proc_open($cmdline . ' &', [], $foo, $this->basePath);
210                 }
211
212                 if (!is_resource($resource)) {
213                         $this->logger->warning('We got no resource for command.', ['command' => $cmdline]);
214                         return;
215                 }
216
217                 proc_close($resource);
218
219                 $this->logger->info('Executed "proc_open"', ['command' => $cmdline, 'callstack' => System::callstack(10)]);
220         }
221
222         /**
223          * Returns a string with a callstack. Can be used for logging.
224          *
225          * @param integer $depth  How many calls to include in the stacks after filtering
226          * @param int     $offset How many calls to shave off the top of the stack, for example if
227          *                        this is called from a centralized method that isn't relevant to the callstack
228          * @return string
229          */
230         public static function callstack(int $depth = 4, int $offset = 0): string
231         {
232                 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
233
234                 // We remove at least the first two items from the list since they contain data that we don't need.
235                 $trace = array_slice($trace, 2 + $offset);
236
237                 $callstack = [];
238                 $previous = ['class' => '', 'function' => '', 'database' => false];
239
240                 // The ignore list contains all functions that are only wrapper functions
241                 $ignore = ['call_user_func_array'];
242
243                 while ($func = array_pop($trace)) {
244                         if (!empty($func['class'])) {
245                                 if (in_array($previous['function'], ['insert', 'fetch', 'toArray', 'exists', 'count', 'selectFirst', 'selectToArray',
246                                         'select', 'update', 'delete', 'selectFirstForUser', 'selectForUser'])
247                                         && (substr($previous['class'], 0, 15) === 'Friendica\Model')) {
248                                         continue;
249                                 }
250
251                                 // Don't show multiple calls from the Database classes to show the essential parts of the callstack
252                                 $func['database'] = in_array($func['class'], ['Friendica\Database\DBA', 'Friendica\Database\Database']);
253                                 if (!$previous['database'] || !$func['database']) {     
254                                         $classparts = explode("\\", $func['class']);
255                                         $callstack[] = array_pop($classparts).'::'.$func['function'];
256                                         $previous = $func;
257                                 }
258                         } elseif (!in_array($func['function'], $ignore)) {
259                                 $func['database'] = ($func['function'] == 'q');
260                                 $callstack[] = $func['function'];
261                                 $func['class'] = '';
262                                 $previous = $func;
263                         }
264                 }
265
266                 $callstack2 = [];
267                 while ((count($callstack2) < $depth) && (count($callstack) > 0)) {
268                         $callstack2[] = array_pop($callstack);
269                 }
270
271                 return implode(', ', $callstack2);
272         }
273
274         /**
275          * Generic XML return
276          * Outputs a basic dfrn XML status structure to STDOUT, with a <status> variable
277          * of $st and an optional text <message> of $message and terminates the current process.
278          *
279          * @param        $st
280          * @param string $message
281          * @throws \Exception
282          */
283         public static function xmlExit($st, $message = '')
284         {
285                 $result = ['status' => $st];
286
287                 if ($message != '') {
288                         $result['message'] = $message;
289                 }
290
291                 if ($st) {
292                         Logger::notice('xml_status returning non_zero: ' . $st . " message=" . $message);
293                 }
294
295                 header("Content-type: text/xml");
296
297                 $xmldata = ["result" => $result];
298
299                 echo XML::fromArray($xmldata, $xml);
300
301                 exit();
302         }
303
304         /**
305          * Send HTTP status header and exit.
306          *
307          * @param integer $val     HTTP status result value
308          * @param string  $message Error message. Optional.
309          * @param string  $content Response body. Optional.
310          * @throws \Exception
311          */
312         public static function httpExit($val, $message = '', $content = '')
313         {
314                 if ($val >= 400) {
315                         Logger::debug('Exit with error', ['code' => $val, 'message' => $message, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
316                 }
317                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $message);
318
319                 echo $content;
320
321                 exit();
322         }
323
324         public static function jsonError($httpCode, $data, $content_type = 'application/json')
325         {
326                 if ($httpCode >= 400) {
327                         Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'callstack' => System::callstack(20), 'method' => $_SERVER['REQUEST_METHOD'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
328                 }
329                 header($_SERVER["SERVER_PROTOCOL"] . ' ' . $httpCode);
330                 self::jsonExit($data, $content_type);
331         }
332
333         /**
334          * Encodes content to json.
335          *
336          * This function encodes an array to json format
337          * and adds an application/json HTTP header to the output.
338          * After finishing the process is getting killed.
339          *
340          * @param mixed   $x The input content.
341          * @param string  $content_type Type of the input (Default: 'application/json').
342          * @param integer $options JSON options
343          */
344         public static function jsonExit($x, $content_type = 'application/json', int $options = 0) {
345                 header("Content-type: $content_type");
346                 echo json_encode($x, $options);
347                 exit();
348         }
349
350         /**
351          * Generates a random string in the UUID format
352          *
353          * @param bool|string $prefix A given prefix (default is empty)
354          * @return string a generated UUID
355          * @throws \Exception
356          */
357         public static function createUUID($prefix = '')
358         {
359                 $guid = System::createGUID(32, $prefix);
360                 return substr($guid, 0, 8) . '-' . substr($guid, 8, 4) . '-' . substr($guid, 12, 4) . '-' . substr($guid, 16, 4) . '-' . substr($guid, 20, 12);
361         }
362
363         /**
364          * Generates a GUID with the given parameters
365          *
366          * @param int         $size   The size of the GUID (default is 16)
367          * @param bool|string $prefix A given prefix (default is empty)
368          * @return string a generated GUID
369          * @throws \Exception
370          */
371         public static function createGUID($size = 16, $prefix = '')
372         {
373                 if (is_bool($prefix) && !$prefix) {
374                         $prefix = '';
375                 } elseif (empty($prefix)) {
376                         $prefix = hash('crc32', DI::baseUrl()->getHostname());
377                 }
378
379                 while (strlen($prefix) < ($size - 13)) {
380                         $prefix .= mt_rand();
381                 }
382
383                 if ($size >= 24) {
384                         $prefix = substr($prefix, 0, $size - 22);
385                         return str_replace('.', '', uniqid($prefix, true));
386                 } else {
387                         $prefix = substr($prefix, 0, max($size - 13, 0));
388                         return uniqid($prefix);
389                 }
390         }
391
392         /**
393          * Returns the current Load of the System
394          *
395          * @return integer
396          */
397         public static function currentLoad()
398         {
399                 if (!function_exists('sys_getloadavg')) {
400                         return false;
401                 }
402
403                 $load_arr = sys_getloadavg();
404
405                 if (!is_array($load_arr)) {
406                         return false;
407                 }
408
409                 return max($load_arr[0], $load_arr[1]);
410         }
411
412         /**
413          * Redirects to an external URL (fully qualified URL)
414          * If you want to route relative to the current Friendica base, use App->internalRedirect()
415          *
416          * @param string $url  The new Location to redirect
417          * @param int    $code The redirection code, which is used (Default is 302)
418          */
419         public static function externalRedirect($url, $code = 302)
420         {
421                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
422                         Logger::warning('No fully qualified URL provided', ['url' => $url, 'callstack' => self::callstack(20)]);
423                         DI::baseUrl()->redirect($url);
424                 }
425
426                 header("Location: $url");
427
428                 switch ($code) {
429                         case 302:
430                                 throw new FoundException();
431                         case 301:
432                                 throw new MovedPermanentlyException();
433                         case 307:
434                                 throw new TemporaryRedirectException();
435                 }
436
437                 exit();
438         }
439
440         /**
441          * Returns the system user that is executing the script
442          *
443          * This mostly returns something like "www-data".
444          *
445          * @return string system username
446          */
447         public static function getUser()
448         {
449                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
450                         return '';
451                 }
452
453                 $processUser = posix_getpwuid(posix_geteuid());
454                 return $processUser['name'];
455         }
456
457         /**
458          * Checks if a given directory is usable for the system
459          *
460          * @param      $directory
461          * @param bool $check_writable
462          *
463          * @return boolean the directory is usable
464          */
465         public static function isDirectoryUsable($directory, $check_writable = true)
466         {
467                 if ($directory == '') {
468                         Logger::info('Directory is empty. This shouldn\'t happen.');
469                         return false;
470                 }
471
472                 if (!file_exists($directory)) {
473                         Logger::info('Path "' . $directory . '" does not exist for user ' . static::getUser());
474                         return false;
475                 }
476
477                 if (is_file($directory)) {
478                         Logger::info('Path "' . $directory . '" is a file for user ' . static::getUser());
479                         return false;
480                 }
481
482                 if (!is_dir($directory)) {
483                         Logger::info('Path "' . $directory . '" is not a directory for user ' . static::getUser());
484                         return false;
485                 }
486
487                 if ($check_writable && !is_writable($directory)) {
488                         Logger::info('Path "' . $directory . '" is not writable for user ' . static::getUser());
489                         return false;
490                 }
491
492                 return true;
493         }
494
495         /**
496          * Exit method used by asynchronous update modules
497          *
498          * @param string $o
499          */
500         public static function htmlUpdateExit($o)
501         {
502                 header("Content-type: text/html");
503                 echo "<!DOCTYPE html><html><body>\r\n";
504                 // We can remove this hack once Internet Explorer recognises HTML5 natively
505                 echo "<section>";
506                 // reportedly some versions of MSIE don't handle tabs in XMLHttpRequest documents very well
507                 echo str_replace("\t", "       ", $o);
508                 echo "</section>";
509                 echo "</body></html>\r\n";
510                 exit();
511         }
512
513         /**
514          * Fetch the temp path of the system
515          *
516          * @return string Path for temp files
517          */
518         public static function getTempPath()
519         {
520                 $temppath = DI::config()->get("system", "temppath");
521
522                 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
523                         // We have a temp path and it is usable
524                         return BasePath::getRealPath($temppath);
525                 }
526
527                 // We don't have a working preconfigured temp path, so we take the system path.
528                 $temppath = sys_get_temp_dir();
529
530                 // Check if it is usable
531                 if (($temppath != "") && System::isDirectoryUsable($temppath)) {
532                         // Always store the real path, not the path through symlinks
533                         $temppath = BasePath::getRealPath($temppath);
534
535                         // To avoid any interferences with other systems we create our own directory
536                         $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
537                         if (!is_dir($new_temppath)) {
538                                 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
539                                 mkdir($new_temppath);
540                         }
541
542                         if (System::isDirectoryUsable($new_temppath)) {
543                                 // The new path is usable, we are happy
544                                 DI::config()->set("system", "temppath", $new_temppath);
545                                 return $new_temppath;
546                         } else {
547                                 // We can't create a subdirectory, strange.
548                                 // But the directory seems to work, so we use it but don't store it.
549                                 return $temppath;
550                         }
551                 }
552
553                 // Reaching this point means that the operating system is configured badly.
554                 return '';
555         }
556
557         /**
558          * Returns the path where spool files are stored
559          *
560          * @return string Spool path
561          */
562         public static function getSpoolPath()
563         {
564                 $spoolpath = DI::config()->get('system', 'spoolpath');
565                 if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
566                         // We have a spool path and it is usable
567                         return $spoolpath;
568                 }
569
570                 // We don't have a working preconfigured spool path, so we take the temp path.
571                 $temppath = self::getTempPath();
572
573                 if ($temppath != "") {
574                         // To avoid any interferences with other systems we create our own directory
575                         $spoolpath = $temppath . "/spool";
576                         if (!is_dir($spoolpath)) {
577                                 mkdir($spoolpath);
578                         }
579
580                         if (System::isDirectoryUsable($spoolpath)) {
581                                 // The new path is usable, we are happy
582                                 DI::config()->set("system", "spoolpath", $spoolpath);
583                                 return $spoolpath;
584                         } else {
585                                 // We can't create a subdirectory, strange.
586                                 // But the directory seems to work, so we use it but don't store it.
587                                 return $temppath;
588                         }
589                 }
590
591                 // Reaching this point means that the operating system is configured badly.
592                 return "";
593         }
594 }