summaryrefslogtreecommitdiffstats
path: root/library/Director/Resolver/HostServiceBlacklist.php
blob: 606855a1e2b3f5154ac769019645e68f83bd446a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php

namespace Icinga\Module\Director\Resolver;

use Icinga\Module\Director\Db;
use Icinga\Module\Director\Objects\IcingaService;

class HostServiceBlacklist
{
    /** @var Db */
    protected $db;

    protected $table = 'icinga_host_service_blacklist';

    protected $mappings;

    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    protected function loadMappings()
    {
        $db = $this->db->getDbAdapter();
        $query = $db->select()->from(['hsb' => $this->table], [
            'host_name' => 'h.object_name',
            'service_id' => 'hsb.service_id'
        ])->join(
            ['h' => 'icinga_host'],
            'hsb.host_id = h.id',
            []
        );

        $result = [];
        foreach ($db->fetchAll($query) as $row) {
            if (array_key_exists($row->service_id, $result)) {
                $result[$row->service_id][] = $row->host_name;
            } else {
                $result[$row->service_id] = [$row->host_name];
            }
        }

        return $result;
    }

    public function preloadMappings()
    {
        $this->mappings = $this->loadMappings();

        return $this;
    }

    public function getBlacklistedHostnamesForService(IcingaService $service)
    {
        if ($this->mappings === null) {
            return $this->fetchMappingsForService($service);
        } else {
            return $this->getPreLoadedMappingsForService($service);
        }
    }

    public function fetchMappingsForService(IcingaService $service)
    {
        if (! $service->hasBeenLoadedFromDb() || $service->get('id') === null) {
            return [];
        }

        $db = $this->db->getDbAdapter();
        $query = $db->select()->from(['hsb' => $this->table], [
            'host_name' => 'h.object_name',
            'service_id' => 'hsb.service_id'
        ])->join(
            ['h' => 'icinga_host'],
            'hsb.host_id = h.id',
            []
        )->where('hsb.service_id = ?', $service->get('id'));

        return $db->fetchCol($query);
    }

    public function getPreLoadedMappingsForService(IcingaService $service)
    {
        if ($this->mappings !== null
            && array_key_exists($service->get('id'), $this->mappings)
        ) {
            return $this->mappings[$service->get('id')];
        }

        return [];
    }
}