Passed
Push — master ( 0e59e1...fddcd5 )
by Nils
02:37
created

Collector   A

Complexity

Total Complexity 14

Size/Duplication

Total Lines 95
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 54
c 4
b 0
f 0
dl 0
loc 95
rs 10
wmc 14

3 Methods

Rating   Name   Duplication   Size   Complexity  
B calculateNetworkThroughput() 0 39 8
A __construct() 0 4 1
A collect() 0 42 5
1
<?php
2
3
namespace Startwind\Inventorio\Metrics\Collector;
4
5
use Startwind\Inventorio\Exec\File;
6
use Startwind\Inventorio\Exec\Runner;
7
use Startwind\Inventorio\Exec\System;
8
use Startwind\Inventorio\Metrics\Collector\Metric\Metric;
9
use Startwind\Inventorio\Metrics\Collector\Metric\Webserver\ApacheAccessLogMetric;
10
use Startwind\Inventorio\Metrics\Collector\Metric\Webserver\ApacheErrorLogMetric;
11
use Startwind\Inventorio\Metrics\Memory\Memory;
12
13
class Collector
14
{
15
    private const MEMORY_KEY = 'net_traffic_history';
16
17
    private array $metrics = [];
18
19
    public function __construct()
20
    {
21
        $this->metrics[] = new ApacheAccessLogMetric();
22
        $this->metrics[] = new ApacheErrorLogMetric();
23
    }
24
25
    public function collect(): array
26
    {
27
        $runner = Runner::getInstance();
28
        $system = System::getInstance();
29
30
        $totalMem = (int)$runner->run("grep MemTotal /proc/meminfo | awk '{print $2}'")->getOutput() + 1;
31
        $freeMem = (int)$runner->run("grep MemAvailable /proc/meminfo | awk '{print $2}'")->getOutput();
32
        $usedMem = $totalMem - $freeMem;
33
        $usedMemPercent = round(($usedMem / $totalMem) * 100, 2);
34
35
        $loadAvg = (float)$system->getLoadAverage()[1];
36
        $cpuCores = (int)$runner->run("nproc")->getOutput();
37
38
        $cpuUsagePercent = ($cpuCores > 0)
39
            ? round(($loadAvg / $cpuCores) * 100, 1)
40
            : 0;
41
42
        $diskTotal = $system->getDiskTotalSpace('/');
43
        $diskFree = $system->getDiskFreeSpace('/');
44
45
        $diskUsedPercent = ($diskTotal > 0)
46
            ? round((($diskTotal - $diskFree) / $diskTotal) * 100, 1)
47
            : 0;
48
49
        $metricResults = [
50
            'memory-usage' => $usedMemPercent,
51
            'cpu-usage' => $cpuUsagePercent,
52
            'disk-usage' => $diskUsedPercent,
53
            'network-throughput-eth0' => $this->calculateNetworkThroughput('eth0')
54
        ];
55
56
        foreach ($this->metrics as $metric) {
57
            /** @var Metric $metric */
58
            if ($metric->isApplicable()) {
59
                $lastValue = Memory::getInstance()->getLastData($metric->getName());
60
                $currentValue = $metric->getValue($lastValue);
61
                Memory::getInstance()->addData($metric->getName(), $currentValue);
62
                $metricResults[$metric->getName()] = $currentValue;
63
            }
64
        }
65
66
        return $metricResults;
67
    }
68
69
    function calculateNetworkThroughput($interface): float
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
70
    {
71
        $memory = Memory::getInstance();
72
73
        $file = new File();
74
75
        if (!$file->fileExists('/proc/net/dev')) return 0;
76
77
        $lines = $file->getContents('/proc/net/dev', true);
78
        foreach ($lines as $line) {
79
            if (strpos($line, $interface . ':') !== false) {
80
                $parts = preg_split('/\s+/', trim($line));
81
                $rx = (int)$parts[1];
82
                $tx = (int)$parts[9];
83
                $total = $rx + $tx;
84
                break;
85
            }
86
        }
87
88
        if (!isset($total)) return 0;
89
90
        $history = $memory->getData(self::MEMORY_KEY) ?? [];
91
92
        if (empty($history)) {
93
            $lastTotal = 0;
94
        } else {
95
            $lastTotal = end($history);
96
        }
97
98
        if ($total < $lastTotal || $lastTotal === 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $total does not seem to be defined for all execution paths leading up to this point.
Loading history...
99
            $memory->addData(self::MEMORY_KEY, $total);
100
            return $total;
101
        }
102
103
        $throughput = $total - $lastTotal;
104
105
        $memory->addData(self::MEMORY_KEY, $total);
106
107
        return $throughput;
108
    }
109
}
110