summaryrefslogtreecommitdiffstats
path: root/library/Graphite/Web/Controller/MonitoringAwareController.php
blob: d4f1a070d41af79e7245cc3774a31bf3bf610d3d (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
<?php

namespace Icinga\Module\Graphite\Web\Controller;

use ArrayIterator;
use Icinga\Application\Modules\Module;
use Icinga\Data\Filter\Filter;
use Icinga\Data\Filterable;
use Icinga\Exception\ConfigurationError;
use Icinga\Exception\QueryException;
use Icinga\Module\Graphite\ProvidedHook\Icingadb\IcingadbSupport;
use Icinga\Module\Monitoring\Backend\MonitoringBackend;
use Icinga\Module\Monitoring\Data\CustomvarProtectionIterator;
use Icinga\Module\Monitoring\DataView\DataView;
use Icinga\Util\Json;
use Icinga\File\Csv;
use Icinga\Web\Controller;
use Icinga\Web\Url;

abstract class MonitoringAwareController extends Controller
{
    /** @var bool Whether to use icingadb as the backend */
    protected $useIcingadbAsBackend = false;

    /** @var  MonitoringBackend */
    protected $backend;

    /**
     * Restrict the given monitored object query for the currently authenticated user
     *
     * @param   DataView    $dataView
     *
     * @return  DataView                The given data view
     */
    protected function applyMonitoringRestriction(DataView $dataView)
    {
        $this->applyRestriction('monitoring/filter/objects', $dataView);

        return $dataView;
    }

    protected function moduleInit()
    {
        if (Module::exists('icingadb') && IcingadbSupport::useIcingaDbAsBackend()) {
            $this->useIcingadbAsBackend = true;

            return;
        }

        $this->backend = MonitoringBackend::instance($this->_getParam('backend'));
        $this->view->url = Url::fromRequest();
    }


    protected function handleFormatRequest($query)
    {
        $desiredContentType = $this->getRequest()->getHeader('Accept');
        if ($desiredContentType === 'application/json') {
            $desiredFormat = 'json';
        } elseif ($desiredContentType === 'text/csv') {
            $desiredFormat = 'csv';
        } else {
            $desiredFormat = strtolower($this->params->get('format', 'html'));
        }

        if ($desiredFormat !== 'html' && ! $this->params->has('limit')) {
            $query->limit();  // Resets any default limit and offset
        }

        switch ($desiredFormat) {
            case 'sql':
                echo '<pre>'
                    . htmlspecialchars(wordwrap($query->dump()))
                    . '</pre>';
                exit;
            case 'json':
                $response = $this->getResponse();
                $response
                    ->setHeader('Content-Type', 'application/json')
                    ->setHeader('Cache-Control', 'no-store')
                    ->setHeader(
                        'Content-Disposition',
                        'inline; filename=' . $this->getRequest()->getActionName() . '.json'
                    )
                    ->appendBody(
                        Json::sanitize(
                            iterator_to_array(
                                new CustomvarProtectionIterator(
                                    new ArrayIterator($query->fetchAll())
                                )
                            )
                        )
                    )
                    ->sendResponse();
                exit;
            case 'csv':
                $response = $this->getResponse();
                $response
                    ->setHeader('Content-Type', 'text/csv')
                    ->setHeader('Cache-Control', 'no-store')
                    ->setHeader(
                        'Content-Disposition',
                        'attachment; filename=' . $this->getRequest()->getActionName() . '.csv'
                    )
                    ->appendBody((string) Csv::fromQuery(new CustomvarProtectionIterator($query)))
                    ->sendResponse();
                exit;
        }
    }

    /**
     * Apply a restriction of the authenticated on the given filterable
     *
     * @param   string      $name       Name of the restriction
     * @param   Filterable  $filterable Filterable to restrict
     *
     * @return  Filterable  The filterable having the restriction applied
     */
    protected function applyRestriction($name, Filterable $filterable)
    {
        $filterable->applyFilter($this->getRestriction($name));
        return $filterable;
    }

    /**
     * Get a restriction of the authenticated
     *
     * @param   string $name        Name of the restriction
     *
     * @return  Filter              Filter object
     * @throws  ConfigurationError  If the restriction contains invalid filter columns
     */
    protected function getRestriction($name)
    {
        $restriction = Filter::matchAny();
        $restriction->setAllowedFilterColumns(array(
            'host_name',
            'hostgroup_name',
            'instance_name',
            'service_description',
            'servicegroup_name',
            function ($c) {
                return preg_match('/^_(?:host|service)_/i', $c);
            }
        ));
        foreach ($this->getRestrictions($name) as $filter) {
            if ($filter === '*') {
                return Filter::matchAll();
            }
            try {
                $restriction->addFilter(Filter::fromQueryString($filter));
            } catch (QueryException $e) {
                throw new ConfigurationError(
                    $this->translate(
                        'Cannot apply restriction %s using the filter %s. You can only use the following columns: %s'
                    ),
                    $name,
                    $filter,
                    implode(', ', array(
                        'instance_name',
                        'host_name',
                        'hostgroup_name',
                        'service_description',
                        'servicegroup_name',
                        '_(host|service)_<customvar-name>'
                    )),
                    $e
                );
            }
        }

        if ($restriction->isEmpty()) {
            return Filter::matchAll();
        }

        return $restriction;
    }
}