1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Innmind\Server\Status\Facade\Memory; |
5
|
|
|
|
6
|
|
|
use Innmind\Server\Status\{ |
7
|
|
|
Server\Memory, |
8
|
|
|
Server\Memory\Bytes, |
9
|
|
|
Exception\MemoryUsageNotAccessible |
10
|
|
|
}; |
11
|
|
|
use Innmind\Immutable\{ |
12
|
|
|
Str, |
13
|
|
|
Map |
14
|
|
|
}; |
15
|
|
|
use Symfony\Component\Process\Process; |
16
|
|
|
|
17
|
|
|
final class LinuxFacade |
18
|
|
|
{ |
19
|
|
|
private static $entries = [ |
20
|
|
|
'MemTotal' => 'total', |
21
|
|
|
'Active' => 'active', |
22
|
|
|
'Inactive' => 'inactive', |
23
|
|
|
'MemFree' => 'free', |
24
|
|
|
'SwapCached' => 'swap', |
25
|
|
|
]; |
26
|
|
|
|
27
|
2 |
|
public function __invoke(): Memory |
28
|
|
|
{ |
29
|
2 |
|
$process = new Process('cat /proc/meminfo'); |
30
|
2 |
|
$process->run(); |
31
|
|
|
|
32
|
2 |
|
if (!$process->isSuccessful()) { |
33
|
|
|
throw new MemoryUsageNotAccessible; |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
$amounts = (new Str($process->getOutput())) |
37
|
2 |
|
->trim() |
38
|
2 |
|
->split("\n") |
39
|
2 |
|
->filter(static function(Str $line): bool { |
40
|
2 |
|
return $line->matches( |
41
|
2 |
|
'~^('.implode('|', array_keys(self::$entries)).'):~' |
42
|
|
|
); |
43
|
2 |
|
}) |
44
|
2 |
|
->reduce( |
45
|
2 |
|
new Map('string', 'int'), |
46
|
2 |
|
static function(Map $map, Str $line): Map { |
47
|
2 |
|
$elements = $line->capture('~^(?P<key>[a-zA-Z]+): +(?P<value>\d+) kB$~'); |
48
|
|
|
|
49
|
2 |
|
return $map->put( |
50
|
2 |
|
self::$entries[(string) $elements->get('key')], |
51
|
2 |
|
((int) (string) $elements->get('value')) * Bytes::BYTES |
52
|
|
|
); |
53
|
2 |
|
} |
54
|
|
|
); |
55
|
|
|
|
56
|
|
|
$used = $amounts->get('total') - $amounts->get('free'); |
57
|
|
|
$wired = $used - $amounts->get('active') - $amounts->get('inactive'); |
58
|
|
|
|
59
|
|
|
return new Memory( |
60
|
|
|
new Bytes($amounts->get('total')), |
61
|
|
|
new Bytes($wired), |
62
|
|
|
new Bytes($amounts->get('active')), |
63
|
|
|
new Bytes($amounts->get('free')), |
64
|
|
|
new Bytes($amounts->get('swap')), |
65
|
|
|
new Bytes($used) |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|