summaryrefslogtreecommitdiffstats
path: root/library/Graphite/Graphing/MetricsQuery.php
blob: 93d0c907c17be22401241596292e3fd7f69a9a9f (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
<?php

namespace Icinga\Module\Graphite\Graphing;

use Icinga\Data\Fetchable;
use Icinga\Data\Filter\Filter;
use Icinga\Data\Filterable;
use Icinga\Data\Queryable;
use Icinga\Exception\NotImplementedError;
use Icinga\Module\Graphite\GraphiteUtil;
use Icinga\Module\Graphite\Util\IcingadbUtils;
use Icinga\Module\Graphite\Util\MacroTemplate;
use Icinga\Module\Graphite\Util\InternalProcessTracker as IPT;
use Icinga\Module\Icingadb\Compat\UrlMigrator;
use Icinga\Module\Icingadb\Model\Host;
use Icinga\Module\Monitoring\Object\Macro;
use Icinga\Module\Monitoring\Object\MonitoredObject;
use Icinga\Util\Json;
use Icinga\Web\Url;
use InvalidArgumentException;
use ipl\Orm\Model;
use ipl\Stdlib\Filter as IplFilter;

/**
 * Queries a {@link MetricsDataSource}
 */
class MetricsQuery implements Queryable, Filterable, Fetchable
{
    /**
     * @var MetricsDataSource
     */
    protected $dataSource;

    /**
     * The base metrics pattern
     *
     * @var MacroTemplate
     */
    protected $base;

    /**
     * Extension of {@link base}
     *
     * @var string[]
     */
    protected $filter = [];

    /**
     * The object to render the graphs for
     *
     * @var MonitoredObject|Model
     */
    protected $object;

    /**
     * Constructor
     *
     * @param   MetricsDataSource   $dataSource
     */
    public function __construct(MetricsDataSource $dataSource)
    {
        $this->dataSource = $dataSource;
    }

    public function from($target, array $fields = null)
    {
        if ($fields !== null) {
            throw new InvalidArgumentException('Fields are not applicable to this kind of query');
        }

        try {
            $this->base = $target instanceof MacroTemplate ? $target : new MacroTemplate((string) $target);
        } catch (InvalidArgumentException $e) {
            throw new InvalidArgumentException('Bad target', $e->getCode(), $e);
        }

        return $this;
    }

    public function applyFilter(Filter $filter)
    {
        throw new NotImplementedError(__METHOD__);
    }

    public function setFilter(Filter $filter)
    {
        throw new NotImplementedError(__METHOD__);
    }

    public function getFilter()
    {
        throw new NotImplementedError(__METHOD__);
    }

    public function addFilter(Filter $filter)
    {
        throw new NotImplementedError(__METHOD__);
    }

    public function where($condition, $value = null)
    {
        $this->filter[$condition] = $this->escapeMetricStep($value);

        return $this;
    }

    public function fetchAll()
    {
        $result = [];
        foreach ($this->fetchColumn() as $metric) {
            $result[] = (object) ['metric' => $metric];
        }

        return $result;
    }

    public function fetchRow()
    {
        $result = $this->fetchColumn();
        return empty($result) ? false : (object) ['metric' => $result[0]];
    }

    public function fetchColumn()
    {
        $filter = [];
        foreach ($this->base->getMacros() as $macro) {
            if (isset($this->filter[$macro])) {
                $filter[$macro] = $this->filter[$macro];
                continue;
            }

            if (strpos($macro, '.') === false) {
                continue;
            }

            $workaroundMacro = str_replace('.', '_', $macro);
            if ($this->object instanceof Model) {
                // icingadb macro
                $tranformFilter = UrlMigrator::transformFilter(
                    IplFilter::equal($workaroundMacro, ''),
                    $this->object instanceof Host ? 'hosts' : 'services'
                );

                if ($tranformFilter === false) {
                    continue;
                }

                $migratedMacro = $tranformFilter->getColumn();

                if ($migratedMacro === $workaroundMacro) {
                    $workaroundMacro = $macro;
                } else {
                    $workaroundMacro = $migratedMacro;
                }

                $icingadbMacros = IcingadbUtils::getInstance();
                $result = $icingadbMacros->resolveMacro($workaroundMacro, $this->object);
            } else {
                if ($workaroundMacro === 'service_name') {
                    $workaroundMacro = 'service_description';
                }

                $result = Macro::resolveMacro($workaroundMacro, $this->object);
            }

            if ($result !== $workaroundMacro) {
                $filter[$macro] = $this->escapeMetricStep($result);
            }
        }

        $client = $this->dataSource->getClient();
        $url = Url::fromPath('metrics/expand', [
            'query' => $this->base->resolve($filter, '*')
        ]);
        $res = Json::decode($client->request($url));
        natsort($res->results);

        IPT::recordf('Fetched %s metric(s) from %s', count($res->results), (string) $client->completeUrl($url));

        return array_values($res->results);
    }

    public function fetchOne()
    {
        $result = $this->fetchColumn();
        return empty($result) ? false : $result[0];
    }

    public function fetchPairs()
    {
        throw new NotImplementedError(__METHOD__);
    }

    /**
     * Set the object to render the graphs for
     *
     * @param MonitoredObject|Model $object
     *
     * @return $this
     */
    public function setObject($object)
    {
        $this->object = $object;

        return $this;
    }

    /**
     * Escapes a string for usage in a Graphite metric path between two dots
     *
     * @param   string  $step
     *
     * @return  string
     */
    protected function escapeMetricStep($step)
    {
        return preg_replace('/[^a-zA-Z0-9\*\-:^[\]$#%\']/', '_', $step);
    }
}