summaryrefslogtreecommitdiffstats
path: root/library/Cube/IcingaDb/IcingaDbCube.php
blob: 44c76197ff451689379675cdeb132d4fc19888a4 (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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
<?php

// Icinga Web 2 Cube Module | (c) 2022 Icinga GmbH | GPLv2

namespace Icinga\Module\Cube\IcingaDb;

use Icinga\Module\Cube\Cube;
use Icinga\Module\Icingadb\Common\Auth;
use Icinga\Module\Icingadb\Common\Database;
use Icinga\Module\Icingadb\Model\Host;
use Icinga\Module\Icingadb\Model\Service;
use ipl\Orm\Common\SortUtil;
use ipl\Orm\Query;
use ipl\Sql\Adapter\Pgsql;
use ipl\Sql\Expression;
use ipl\Sql\Select;
use ipl\Stdlib\BaseFilter;

abstract class IcingaDbCube extends Cube
{
    use Auth;
    use BaseFilter;
    use Database;

    public const SLICE_PREFIX = 'slice.';
    public const IS_USING_ICINGADB = true;

    /** @var bool Whether to show problems only */
    protected $problemsOnly = false;

    /** @var string Sort param used to sort dimensions by value */
    public const DIMENSION_VALUE_SORT_PARAM = 'value';

    /** @var string Sort param used to sort dimensions by severity */
    public const DIMENSION_SEVERITY_SORT_PARAM = 'severity';

    /** @var Query The inner query fetching all required data */
    protected $innerQuery;

    /** @var Select The rollup query, creating grouped sums over innerQuery */
    protected $rollupQuery;

    /** @var Select The outer query, orders respecting NULL values, rollup first */
    protected $fullQuery;

    protected $objectsFilter;

    /** @var array The sort order of dimensions, column as key and direction as value */
    protected $sortBy;

    abstract public function getObjectsFilter();
    /**
     * An IcingaDbCube must provide a list of all available columns
     *
     * This is a key/value array with the key being the fact name / column alias
     * and
     *
     * @return array
     */
    abstract public function getAvailableFactColumns();

    /**
     * @return Query
     */
    abstract public function prepareInnerQuery();

    /**
     * Get our inner query
     *
     * Hint: mostly used to get rid of NULL values
     *
     * @return Query
     */
    public function innerQuery()
    {
        if ($this->innerQuery === null) {
            $this->innerQuery = $this->prepareInnerQuery();
        }

        return $this->innerQuery;
    }

    /**
     * Get our rollup query
     *
     * @return Select
     */
    protected function rollupQuery()
    {
        if ($this->rollupQuery === null) {
            $this->rollupQuery = $this->prepareRollupQuery();
        }

        return $this->rollupQuery;
    }

    /**
     * Add a specific named dimension
     *
     * @param string $name
     * @return $this
     */
    public function addDimensionByName($name)
    {
        $this->addDimension($this->createDimension($name));

        return $this;
    }

    /**
     * Set whether to show problems only
     *
     * @param bool $problemOnly
     *
     * @return $this
     */
    public function problemsOnly(bool $problemOnly = true): self
    {
        $this->problemsOnly = $problemOnly;

        return $this;
    }


    /**
     * Get whether to show problems only
     *
     * @return bool
     */
    public function isProblemsOnly(): bool
    {
        return $this->problemsOnly;
    }

    /**
     * Fetch the host variable dimensions
     *
     * @return array
     */
    public function fetchHostVariableDimensions(): array
    {
        $query = Host::on($this->getDb())
            ->with('customvar_flat')
            ->columns('customvar_flat.flatname')
            ->orderBy('customvar_flat.flatname');

        $this->applyRestrictions($query);

        $query->getSelectBase()->groupBy('flatname');

        $dimensions = [];
        foreach ($query as $row) {
            // Replaces array index notations with [*] to get results for arbitrary indexes
            $name = preg_replace('/\\[\d+](?=\\.|$)/', '[*]', $row->customvar_flat->flatname);
            $name = strtolower($name);
            $dimensions[CustomVariableDimension::HOST_PREFIX . $name] = 'Host ' . $name;
        }

        return $dimensions;
    }

    /**
     * Fetch the service variable dimensions
     *
     * @return array
     */
    public function fetchServiceVariableDimensions(): array
    {
        $query = Service::on($this->getDb())
            ->with('customvar_flat')
            ->columns('customvar_flat.flatname')
            ->orderBy('customvar_flat.flatname');

        $this->applyRestrictions($query);

        $query->getSelectBase()->groupBy('flatname');

        $dimensions = [];
        foreach ($query as $row) {
            // Replaces array index notations with [*] to get results for arbitrary indexes
            $name = preg_replace('/\\[\d+](?=\\.|$)/', '[*]', $row->customvar_flat->flatname);
            $name = strtolower($name);
            $dimensions[CustomVariableDimension::SERVICE_PREFIX . $name] = 'Service ' . $name;
        }

        return $dimensions;
    }

    /**
     * Set sort by columns
     *
     * @param ?string $sortBy
     *
     * @return $this
     */
    public function sortBy(?string $sortBy): self
    {
        if (empty($sortBy)) {
            return $this;
        }

        $this->sortBy = SortUtil::createOrderBy($sortBy)[0];

        return $this;
    }

    /**
     * Get sort by columns
     *
     * @return ?array Column as key and direction as value
     */
    public function getSortBy(): ?array
    {
        return $this->sortBy;
    }

    /**
     * We first prepare the queries and to finalize it later on
     *
     * This way dimensions can be added one by one, they will be allowed to
     * optionally join additional tables or apply other modifications late
     * in the process
     *
     * @return void
     */
    protected function finalizeInnerQuery()
    {
        $query = $this->innerQuery();
        $select = $query->getSelectBase();

        $columns = [];
        foreach ($this->dimensions as $name => $dimension) {
            $quotedDimension = $this->getDb()->quoteIdentifier([$name]);
            $dimension->addToCube($this);
            $columns[$quotedDimension] = $dimension->getColumnExpression($this);

            if ($this->hasSlice($name)) {
                $select->where(
                    $dimension->getColumnExpression($this) . ' = ?',
                    $this->slices[$name]
                );
            } else {
                $columns[$quotedDimension] = $dimension->getColumnExpression($this);
            }
        }

        $select->columns($columns);

        $this->applyRestrictions($query);
        if ($this->hasBaseFilter()) {
            $query->filter($this->getBaseFilter());
        }
    }

    protected function prepareRollupQuery()
    {
        $dimensions = $this->listDimensions();
        $this->finalizeInnerQuery();

        $columns = [];
        $groupBy = [];
        foreach ($dimensions as $name => $dimension) {
            $quotedDimension = $this->getDb()->quoteIdentifier([$name]);

            $columns[$quotedDimension] = 'f.' . $quotedDimension;
            $groupBy[] = $quotedDimension;
        }

        $availableFacts = $this->getAvailableFactColumns();

        foreach ($this->chosenFacts as $alias) {
            $columns[$alias] = new Expression('SUM(f.' . $availableFacts[$alias] . ')');
        }

        if (! empty($groupBy)) {
            if ($this->getDb()->getAdapter() instanceof Pgsql) {
                $groupBy = 'ROLLUP(' . implode(', ', $groupBy) . ')';
            } else {
                $groupBy[count($groupBy) - 1] .= ' WITH ROLLUP';
            }
        }

        $rollupQuery = new Select();
        $rollupQuery->from(['f' => $this->innerQuery()->assembleSelect()])
            ->columns($columns)
            ->groupBy($groupBy);

        return $rollupQuery;
    }

    protected function prepareFullQuery()
    {
        $rollupQuery = $this->rollupQuery();
        $columns = [];
        $orderBy = [];
        $sortBy = $this->getSortBy();
        foreach ($this->listColumns() as $column) {
            $quotedColumn = $this->getDb()->quoteIdentifier([$column]);
            $columns[$quotedColumn] = 'rollup.' . $quotedColumn;

            if ($this->hasDimension($column)) {
                $orderBy["($quotedColumn IS NOT NULL)"] = null;

                $sortDir = 'ASC';
                if ($sortBy && self::DIMENSION_VALUE_SORT_PARAM === $sortBy[0]) {
                    $sortDir = $sortBy[1] ?? 'ASC';
                }

                $orderBy[$quotedColumn] = $sortDir;
            }
        }

        return (new Select())
            ->from(['rollup' => $rollupQuery])
            ->columns($columns)
            ->orderBy($orderBy);
    }

    /**
     * Lazy-load our full query
     *
     * @return Select
     */
    protected function fullQuery()
    {
        if ($this->fullQuery === null) {
            $this->fullQuery = $this->prepareFullQuery();
        }

        return $this->fullQuery;
    }

    public function fetchAll()
    {
        $query = $this->fullQuery();
        return $this->getDb()->fetchAll($query);
    }
}