summaryrefslogtreecommitdiffstats
path: root/library/Graphite/Graphing/Template.php
blob: a030fb7bb825fa9b33c1f143f7bf3c2d4fbc15fa (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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
<?php

namespace Icinga\Module\Graphite\Graphing;

use Icinga\Application\Config;
use Icinga\Exception\ConfigurationError;
use Icinga\Module\Graphite\Util\MacroTemplate;
use Icinga\Module\Graphite\Util\InternalProcessTracker as IPT;
use Icinga\Module\Monitoring\Object\MonitoredObject;
use InvalidArgumentException;
use ipl\Orm\Model;

class Template
{
    /**
     * The configured icinga.graphite_writer_host_name_template
     *
     * @var MacroTemplate
     */
    protected static $hostNameTemplate;

    /**
     * The configured icinga.graphite_writer_service_name_template
     *
     * @var MacroTemplate
     */
    protected static $serviceNameTemplate;

    /**
     * All curves to show in a chart by name with Graphite Web metric filters and Graphite functions
     *
     * [$curve => [$metricFilter, $function], ...]
     *
     * @var MacroTemplate[][]
     */
    protected $curves = [];

    /**
     * All curves to show in a chart by name with full Graphite Web metric filters and Graphite functions
     *
     * [$curve => [$metricFilter, $function], ...]
     *
     * @var MacroTemplate[][]
     */
    protected $fullCurves;

    /**
     * Additional URL parameters for rendering via Graphite Web
     *
     * [$key => $value, ...]
     *
     * @var MacroTemplate[]
     */
    protected $urlParams = [];

    /**
     * Constructor
     */
    public function __construct()
    {
    }

    /**
     * Get all charts based on this template and applicable to the metrics
     * from the given data source restricted by the given filter
     *
     * @param   MetricsDataSource       $dataSource
     * @param   MonitoredObject|Model   $object    The object to render the graphs for
     * @param   string[]                $filter
     * @param   MacroTemplate[]         $excludeMetrics
     *
     * @return  Chart[]
     */
    public function getCharts(
        MetricsDataSource $dataSource,
        $object,
        array $filter,
        array &$excludeMetrics = []
    ) {
        $metrics = [];
        $metricsUsed = 0;
        $metricsExcluded = 0;

        foreach ($this->getFullCurves() as $curveName => $curve) {
            $fullMetricTemplate = $curve[0];

            $query = $dataSource->select()->setObject($object)->from($fullMetricTemplate);

            foreach ($filter as $key => $value) {
                $query->where($key, $value);
            }

            foreach ($query->fetchColumn() as $metric) {
                foreach ($excludeMetrics as $excludeMetric) {
                    if ($excludeMetric->reverseResolve($metric) !== false) {
                        ++$metricsExcluded;
                        continue 2;
                    }
                }

                $vars = $curve[0]->reverseResolve($metric);
                if ($vars !== false) {
                    $metrics[$curveName][$metric] = $vars;
                    ++$metricsUsed;
                }
            }
        }

        switch (count($metrics)) {
            case 0:
                $metricsCombinations = [];
                break;

            case 1:
                $metricsCombinations = [];

                foreach ($metrics as $curveName => & $curveMetrics) {
                    foreach ($curveMetrics as $metric => & $_) {
                        $metricsCombinations[] = [$curveName => $metric];
                    }
                    unset($_);
                }
                unset($curveMetrics);

                break;

            default:
                $possibleCombinations = [];
                $handledCurves = [];
                foreach ($metrics as $curveName1 => & $metrics1) {
                    $handledCurves[$curveName1] = true;

                    foreach ($metrics as $curveName2 => & $metrics2) {
                        if (! isset($handledCurves[$curveName2])) {
                            foreach ($metrics1 as $metric1 => & $vars1) {
                                foreach ($metrics2 as $metric2 => & $vars2) {
                                    if (
                                        count(array_intersect_assoc($vars1, $vars2))
                                        === count(array_intersect_key($vars1, $vars2))
                                    ) {
                                        $possibleCombinations[$curveName1][$curveName2][$metric1][$metric2] = true;
                                    }
                                }
                                unset($vars2);
                            }
                            unset($vars1);
                        }
                    }
                    unset($metrics2);
                }
                unset($metrics1);

                $metricsCombinations = [];
                $this->combineMetrics($metrics, $possibleCombinations, $metricsCombinations);
        }

        $charts = [];
        foreach ($metricsCombinations as $metricsCombination) {
            $charts[] = new Chart($dataSource->getClient(), $this, $metricsCombination);
        }

        IPT::recordf('Excluded %s metric(s)', $metricsExcluded);
        IPT::recordf('Combined %s metric(s) to %s chart(s)', $metricsUsed, count($charts));

        return $charts;
    }

    /**
     * Fill the given metrics combinations from the given metrics as restricted by the given possible combinations
     *
     * @param   string[][][]    $metrics
     * @param   bool[][][][]    $possibleCombinations
     * @param   string[][]      $metricsCombinations
     * @param   string[]        $currentCombination
     */
    protected function combineMetrics(
        array &$metrics,
        array &$possibleCombinations,
        array &$metricsCombinations,
        array $currentCombination = []
    ) {
        if (empty($currentCombination)) {
            foreach ($metrics as $curveName => & $curveMetrics) {
                foreach ($curveMetrics as $metric => & $_) {
                    $this->combineMetrics(
                        $metrics,
                        $possibleCombinations,
                        $metricsCombinations,
                        [$curveName => $metric]
                    );
                }
                unset($_);

                break;
            }
            unset($curveMetrics);
        } elseif (count($currentCombination) === count($metrics)) {
            $metricsCombinations[] = $currentCombination;
        } else {
            foreach ($metrics as $nextCurveName => & $_) {
                if (! isset($currentCombination[$nextCurveName])) {
                    break;
                }
            }
            unset($_);

            $allowedNextCurveMetricsPerCurrentCurveName = [];
            foreach ($currentCombination as $currentCurveName => $currentCurveMetric) {
                $allowedNextCurveMetricsPerCurrentCurveName[$currentCurveName]
                    = $possibleCombinations[$currentCurveName][$nextCurveName][$currentCurveMetric];
            }

            $allowedNextCurveMetrics = $allowedNextCurveMetricsPerCurrentCurveName[$currentCurveName];
            unset($allowedNextCurveMetricsPerCurrentCurveName[$currentCurveName]);

            foreach ($allowedNextCurveMetricsPerCurrentCurveName as & $allowedMetrics) {
                $allowedNextCurveMetrics = array_intersect_key($allowedNextCurveMetrics, $allowedMetrics);
            }
            unset($allowedMetrics);

            foreach ($allowedNextCurveMetrics as $allowedNextCurveMetric => $_) {
                $nextCombination = $currentCombination;
                $nextCombination[$nextCurveName] = $allowedNextCurveMetric;

                $this->combineMetrics($metrics, $possibleCombinations, $metricsCombinations, $nextCombination);
            }
        }
    }

    /**
     * Get curves to show in a chart by name with Graphite Web metric filters and Graphite functions
     *
     * @return MacroTemplate[][]
     */
    public function getCurves()
    {
        return $this->curves;
    }

    /**
     * Get curves to show in a chart by name with full Graphite Web metric filters and Graphite functions
     *
     * @return MacroTemplate[][]
     */
    public function getFullCurves()
    {
        if ($this->fullCurves === null) {
            $curves = $this->curves;

            foreach ($curves as &$curve) {
                $curve[0] = new MacroTemplate($curve[0]->resolve([
                    'host_name_template'    => static::getHostNameTemplate(),
                    'service_name_template' => static::getServiceNameTemplate(),
                    ''                      => '$$'
                ]));
            }
            unset($curve);

            $this->fullCurves = $curves;
        }

        return $this->fullCurves;
    }

    /**
     * Set curves to show in a chart by name with Graphite Web metric filters and Graphite functions
     *
     * @param MacroTemplate[][] $curves
     *
     * @return $this
     */
    public function setCurves(array $curves)
    {
        $this->curves = $curves;

        return $this;
    }

    /**
     * Get additional URL parameters for Graphite Web
     *
     * @return MacroTemplate[]
     */
    public function getUrlParams()
    {
        return $this->urlParams;
    }

    /**
     * Set additional URL parameters for Graphite Web
     *
     * @param MacroTemplate[]  $urlParams
     *
     * @return $this
     */
    public function setUrlParams(array $urlParams)
    {
        $this->urlParams = $urlParams;

        return $this;
    }

    /**
     * Get {@link hostNameTemplate}
     *
     * @return MacroTemplate
     *
     * @throws  ConfigurationError  If the configuration is invalid
     */
    protected static function getHostNameTemplate()
    {
        if (static::$hostNameTemplate === null) {
            $config = Config::module('graphite');
            $template = $config->get(
                'icinga',
                'graphite_writer_host_name_template',
                'icinga2.$host.name$.host.$host.check_command$'
            );

            try {
                static::$hostNameTemplate = new MacroTemplate($template);
            } catch (InvalidArgumentException $e) {
                throw new ConfigurationError(
                    'Bad icinga.graphite_writer_host_name_template in "%s": %s',
                    $config->getConfigFile(),
                    $e->getMessage()
                );
            }
        }

        return static::$hostNameTemplate;
    }

    /**
     * Get {@link serviceNameTemplate}
     *
     * @return MacroTemplate
     *
     * @throws  ConfigurationError  If the configuration is invalid
     */
    protected static function getServiceNameTemplate()
    {
        if (static::$serviceNameTemplate === null) {
            $config = Config::module('graphite');
            $template = $config->get(
                'icinga',
                'graphite_writer_service_name_template',
                'icinga2.$host.name$.services.$service.name$.$service.check_command$'
            );

            try {
                static::$serviceNameTemplate = new MacroTemplate($template);
            } catch (InvalidArgumentException $e) {
                throw new ConfigurationError(
                    'Bad icinga.graphite_writer_service_name_template in "%s": %s',
                    $config->getConfigFile(),
                    $e->getMessage()
                );
            }
        }

        return static::$serviceNameTemplate;
    }
}