|
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 array $entries = [ |
|
20
|
|
|
'MemTotal' => 'total', |
|
21
|
|
|
'Active' => 'active', |
|
22
|
|
|
'Inactive' => 'inactive', |
|
23
|
|
|
'MemFree' => 'free', |
|
24
|
|
|
'SwapCached' => 'swap', |
|
25
|
|
|
]; |
|
26
|
|
|
|
|
27
|
6 |
|
public function __invoke(): Memory |
|
28
|
|
|
{ |
|
29
|
6 |
|
$process = Process::fromShellCommandline('cat /proc/meminfo'); |
|
30
|
6 |
|
$process->run(); |
|
31
|
|
|
|
|
32
|
6 |
|
if (!$process->isSuccessful()) { |
|
33
|
|
|
throw new MemoryUsageNotAccessible; |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
6 |
|
/** @var Map<string, int> */ |
|
37
|
6 |
|
$amounts = Str::of($process->getOutput()) |
|
38
|
6 |
|
->trim() |
|
39
|
|
|
->split("\n") |
|
40
|
6 |
|
->filter(static function(Str $line): bool { |
|
41
|
6 |
|
return $line->matches( |
|
42
|
|
|
'~^('.\implode('|', \array_keys(self::$entries)).'):~' |
|
43
|
6 |
|
); |
|
44
|
6 |
|
}) |
|
45
|
6 |
|
->reduce( |
|
46
|
|
|
Map::of('string', 'int'), |
|
47
|
6 |
|
static function(Map $map, Str $line): Map { |
|
48
|
|
|
$elements = $line->capture('~^(?P<key>[a-zA-Z]+): +(?P<value>\d+) kB$~'); |
|
49
|
6 |
|
|
|
50
|
6 |
|
return ($map)( |
|
51
|
6 |
|
self::$entries[$elements->get('key')->toString()], |
|
52
|
|
|
((int) $elements->get('value')->toString()) * Bytes::BYTES, |
|
53
|
6 |
|
); |
|
54
|
|
|
}, |
|
55
|
|
|
); |
|
56
|
6 |
|
|
|
57
|
6 |
|
$used = $amounts->get('total') - $amounts->get('free'); |
|
58
|
|
|
$wired = $used - $amounts->get('active') - $amounts->get('inactive'); |
|
59
|
6 |
|
|
|
60
|
6 |
|
return new Memory( |
|
61
|
6 |
|
new Bytes($amounts->get('total')), |
|
62
|
6 |
|
new Bytes($wired), |
|
63
|
6 |
|
new Bytes($amounts->get('active')), |
|
64
|
6 |
|
new Bytes($amounts->get('free')), |
|
65
|
6 |
|
new Bytes($amounts->get('swap')), |
|
66
|
|
|
new Bytes($used), |
|
67
|
|
|
); |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|