Linux.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. declare(strict_types=1);
  3. namespace PhpMyAdmin\Server\SysInfo;
  4. use function array_combine;
  5. use function array_merge;
  6. use function file_get_contents;
  7. use function intval;
  8. use function is_array;
  9. use function is_readable;
  10. use function mb_strpos;
  11. use function mb_substr;
  12. use function preg_match_all;
  13. use function preg_split;
  14. /**
  15. * Linux based SysInfo class
  16. */
  17. class Linux extends Base
  18. {
  19. /**
  20. * The OS name
  21. *
  22. * @var string
  23. */
  24. public $os = 'Linux';
  25. /**
  26. * Gets load information
  27. *
  28. * @return array<string, int> with load data
  29. */
  30. public function loadavg()
  31. {
  32. $buf = file_get_contents('/proc/stat');
  33. if ($buf === false) {
  34. $buf = '';
  35. }
  36. $pos = mb_strpos($buf, "\n");
  37. if ($pos === false) {
  38. $pos = 0;
  39. }
  40. $nums = preg_split(
  41. '/\s+/',
  42. mb_substr(
  43. $buf,
  44. 0,
  45. $pos
  46. )
  47. );
  48. if (! is_array($nums)) {
  49. return ['busy' => 0, 'idle' => 0];
  50. }
  51. return [
  52. 'busy' => (int) $nums[1] + (int) $nums[2] + (int) $nums[3],
  53. 'idle' => (int) $nums[4],
  54. ];
  55. }
  56. /**
  57. * Checks whether class is supported in this environment
  58. *
  59. * @return bool true on success
  60. */
  61. public function supported()
  62. {
  63. return @is_readable('/proc/meminfo') && @is_readable('/proc/stat');
  64. }
  65. /**
  66. * Gets information about memory usage
  67. *
  68. * @return array with memory usage data
  69. */
  70. public function memory()
  71. {
  72. $content = @file_get_contents('/proc/meminfo');
  73. if ($content === false) {
  74. return [];
  75. }
  76. preg_match_all(
  77. SysInfo::MEMORY_REGEXP,
  78. $content,
  79. $matches
  80. );
  81. $mem = array_combine($matches[1], $matches[2]);
  82. if ($mem === false) {
  83. return [];
  84. }
  85. $defaults = [
  86. 'MemTotal' => 0,
  87. 'MemFree' => 0,
  88. 'Cached' => 0,
  89. 'Buffers' => 0,
  90. 'SwapTotal' => 0,
  91. 'SwapFree' => 0,
  92. 'SwapCached' => 0,
  93. ];
  94. $mem = array_merge($defaults, $mem);
  95. foreach ($mem as $idx => $value) {
  96. $mem[$idx] = intval($value);
  97. }
  98. /** @var array<string, int> $mem */
  99. $mem['MemUsed'] = $mem['MemTotal'] - $mem['MemFree'] - $mem['Cached'] - $mem['Buffers'];
  100. $mem['SwapUsed'] = $mem['SwapTotal'] - $mem['SwapFree'] - $mem['SwapCached'];
  101. return $mem;
  102. }
  103. }