summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Redis/VolatileStateResults.php
blob: 186022a30c36fd75b5271484a0f95f77f9a1e032 (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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
<?php

/* Icinga DB Web | (c) 2021 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Redis;

use Exception;
use Generator;
use Icinga\Application\Benchmark;
use Icinga\Module\Icingadb\Common\IcingaRedis;
use Icinga\Module\Icingadb\Model\Host;
use Icinga\Module\Icingadb\Model\Service;
use ipl\Orm\Query;
use ipl\Orm\Resolver;
use ipl\Orm\ResultSet;
use Predis\Client;
use RuntimeException;

class VolatileStateResults extends ResultSet
{
    /** @var Resolver */
    private $resolver;

    /** @var Client */
    private $redis;

    /** @var bool Whether Redis updates were applied */
    private $updatesApplied = false;

    public static function fromQuery(Query $query)
    {
        $self = parent::fromQuery($query);
        $self->resolver = $query->getResolver();

        try {
            $self->redis = IcingaRedis::instance()->getConnection();
        } catch (Exception $e) {
            // The error has already been logged
        }

        return $self;
    }

    /**
     * Get whether Redis is unavailable
     *
     * @return bool
     */
    public function isRedisUnavailable(): bool
    {
        return $this->redis === null;
    }

    public function current()
    {
        if ($this->redis && ! $this->updatesApplied && ! $this->isCacheDisabled) {
            $this->rewind();
        }

        return parent::current();
    }

    public function key(): int
    {
        if ($this->redis && ! $this->updatesApplied && ! $this->isCacheDisabled) {
            $this->rewind();
        }

        return parent::key();
    }

    public function rewind(): void
    {
        if ($this->redis && ! $this->updatesApplied && ! $this->isCacheDisabled) {
            $this->updatesApplied = true;
            $this->advance();

            Benchmark::measure('Applying Redis updates');
            $this->applyRedisUpdates();
            Benchmark::measure('Redis updates applied');
        }

        parent::rewind();
    }

    protected function applyRedisUpdates()
    {
        $type = null;
        $behaviors = null;

        $keys = [];
        $hostStateKeys = [];

        $states = [];
        $hostStates = [];
        foreach ($this as $row) {
            if ($type === null) {
                $behaviors = $this->resolver->getBehaviors($row->state);

                switch (true) {
                    case $row instanceof Host:
                        $type = 'host';
                        break;
                    case $row instanceof Service:
                        $type = 'service';
                        break;
                    default:
                        throw new RuntimeException('Volatile states can only be fetched for hosts and services');
                }
            }

            $states[bin2hex($row->id)] = $row->state;
            if (empty($keys)) {
                $keys = $row->state->getColumns();
            }

            if ($type === 'service' && $row->host instanceof Host) {
                $hostStates[bin2hex($row->host->id)] = $row->host->state;
                if (empty($hostStateKeys)) {
                    $hostStateKeys = $row->host->state->getColumns();
                }
            }
        }

        if (empty($states)) {
            return;
        }

        foreach ($this->fetchStates("icinga:{$type}:state", array_keys($states), $keys) as $id => $data) {
            foreach ($data as $key => $value) {
                $data[$key] = $behaviors->retrieveProperty($value, $key);
            }

            $states[$id]->setProperties($data);
        }

        if ($type === 'service' && ! empty($hostStates)) {
            foreach ($this->fetchStates('icinga:host:state', array_keys($hostStates), $hostStateKeys) as $id => $data) {
                foreach ($data as $key => $value) {
                    $data[$key] = $behaviors->retrieveProperty($value, $key);
                }

                $hostStates[$id]->setProperties($data);
            }
        }
    }

    protected function fetchStates(string $key, array $ids, array $keys): Generator
    {
        $results = $this->redis->hmget($key, $ids);
        foreach ($results as $i => $json) {
            if ($json !== null) {
                $data = json_decode($json, true);
                $keyMap = array_fill_keys($keys, null);
                unset($keyMap['is_overdue']); // Is calculated by Icinga DB, not Icinga 2, hence it's never in redis

                // TODO: Remove once https://github.com/Icinga/icinga2/issues/9427 is fixed
                $data['state_type'] = $data['state_type'] === 0 ? 'soft' : 'hard';

                yield $ids[$i] => array_intersect_key(array_merge($keyMap, $data), $keyMap);
            }
        }
    }
}