Passed
Push — master ( 6edd3f...805485 )
by Nils
02:47
created

DockerCollector::collect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Startwind\Inventorio\Collector\Container;
4
5
use Startwind\Inventorio\Collector\Collector;
6
use Startwind\Inventorio\Exec\File;
7
use Startwind\Inventorio\Exec\Runner;
8
9
class DockerCollector implements Collector
10
{
11
    public function getIdentifier(): string
12
    {
13
        return 'ContainerDocker';
14
    }
15
16
    private function isDockerInstalled(): bool
17
    {
18
        return Runner::getInstance()->commandExists('docker');
19
    }
20
21
    private function getRunningDockerContainers(): array
22
    {
23
        $runner = new Runner();
24
25
        if (!$runner->commandExists('docker')) return [];
26
27
        $cmd = 'docker ps --format {{.ID}}|{{.Image}}|{{.Names}}|{{.Ports}}';
28
        $output = Runner::getInstance()->run($cmd)->getOutput();
29
30
        $lines = explode("\n", trim($output));
31
        $containers = [];
32
33
        foreach ($lines as $line) {
34
            if (empty($line)) continue;
35
36
            [$id, $image, $name, $ports] = explode('|', $line);
37
            $containers[] = [
38
                'id' => $id,
39
                'image' => $image,
40
                'name' => $name,
41
                'ports' => $ports,
42
            ];
43
        }
44
45
        return $containers;
46
    }
47
48
    public function collect(): array
49
    {
50
        return [
51
            'isDockerInstalled' => $this->isDockerInstalled(),
52
            'isInsideDocker' => File::getInstance()->fileExists('/.dockerenv'),
53
            'containers' => $this->getRunningDockerContainers(),
54
        ];
55
    }
56
}
57