summaryrefslogtreecommitdiffstats
path: root/modules/monitoring/application/forms/Config/BackendConfigForm.php
blob: 5ed42e1dbc2e189e1b3dd76475246266f04c6224 (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
365
366
367
<?php
/* Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

namespace Icinga\Module\Monitoring\Forms\Config;

use Exception;
use InvalidArgumentException;
use Icinga\Application\Config;
use Icinga\Data\ConfigObject;
use Icinga\Data\ResourceFactory;
use Icinga\Exception\ConfigurationError;
use Icinga\Exception\IcingaException;
use Icinga\Exception\NotFoundError;
use Icinga\Forms\ConfigForm;
use Icinga\Web\Form;

/**
 * Form for managing monitoring backends
 */
class BackendConfigForm extends ConfigForm
{
    /**
     * The available monitoring backend resources split by type
     *
     * @var array
     */
    protected $resources;

    /**
     * The backend to load when displaying the form for the first time
     *
     * @var string
     */
    protected $backendToLoad;

    /**
     * Initialize this form
     */
    public function init()
    {
        $this->setName('form_config_monitoring_backends');
        $this->setSubmitLabel($this->translate('Save Changes'));
    }

    /**
     * Set the resource configuration to use
     *
     * @param   Config  $resourceConfig     The resource configuration
     *
     * @return  $this
     *
     * @throws  ConfigurationError          In case there are no valid monitoring backend resources
     */
    public function setResourceConfig(Config $resourceConfig)
    {
        $resources = array();
        foreach ($resourceConfig as $name => $resource) {
            if ($resource->type === 'db') {
                $resources['ido'][$name] = $name;
            }
        }

        if (empty($resources)) {
            throw new ConfigurationError($this->translate(
                'Could not find any valid monitoring backend resources. Please configure a database resource first.'
            ));
        }

        $this->resources = $resources;
        return $this;
    }

    /**
     * Populate the form with the given backend's config
     *
     * @param   string  $name
     *
     * @return  $this
     *
     * @throws  NotFoundError   In case no backend with the given name is found
     */
    public function load($name)
    {
        if (! $this->config->hasSection($name)) {
            throw new NotFoundError('No monitoring backend called "%s" found', $name);
        }

        $this->backendToLoad = $name;
        return $this;
    }

    /**
     * Add a new monitoring backend
     *
     * The backend to add is identified by the array-key `name'.
     *
     * @param   array   $data
     *
     * @return  $this
     *
     * @throws  InvalidArgumentException    In case $data does not contain a backend name
     * @throws  IcingaException             In case a backend with the same name already exists
     */
    public function add(array $data)
    {
        if (! isset($data['name'])) {
            throw new InvalidArgumentException('Key \'name\' missing');
        }

        $backendName = $data['name'];
        if ($this->config->hasSection($backendName)) {
            throw new IcingaException(
                $this->translate('A monitoring backend with the name "%s" does already exist'),
                $backendName
            );
        }

        unset($data['name']);
        $this->config->setSection($backendName, $data);
        return $this;
    }

    /**
     * Edit a monitoring backend
     *
     * @param   string  $name
     * @param   array   $data
     *
     * @return  $this
     *
     * @throws  NotFoundError   In case no backend with the given name is found
     */
    public function edit($name, array $data)
    {
        if (! $this->config->hasSection($name)) {
            throw new NotFoundError('No monitoring backend called "%s" found', $name);
        }

        $backendConfig = $this->config->getSection($name);
        if (isset($data['name'])) {
            if ($data['name'] !== $name) {
                $this->config->removeSection($name);
                $name = $data['name'];
            }

            unset($data['name']);
        }

        $backendConfig->merge($data);
        $this->config->setSection($name, $backendConfig);
        return $this;
    }

    /**
     * Remove a monitoring backend
     *
     * @param   string  $name
     *
     * @return  $this
     */
    public function delete($name)
    {
        $this->config->removeSection($name);
        return $this;
    }

    /**
     * Create and add elements to this form
     *
     * @param   array   $formData
     */
    public function createElements(array $formData)
    {
        $this->addElement(
            'checkbox',
            'disabled',
            array(
                'label'     => $this->translate('Disable This Backend')
            )
        );
        $this->addElement(
            'text',
            'name',
            array(
                'required'      => true,
                'label'         => $this->translate('Backend Name'),
                'description'   => $this->translate(
                    'The name of this monitoring backend that is used to differentiate it from others'
                )
            )
        );

        $resourceType = isset($formData['type']) ? $formData['type'] : null;

        $resourceTypes = array();
        if ($resourceType === 'ido' || array_key_exists('ido', $this->resources)) {
            $resourceTypes['ido'] = 'IDO Backend';
        }

        if ($resourceType === null) {
            $resourceType = key($resourceTypes);
        }

        $this->addElement(
            'select',
            'type',
            array(
                'required'      => true,
                'autosubmit'    => true,
                'label'         => $this->translate('Backend Type'),
                'description'   => $this->translate(
                    'The type of data source used for retrieving monitoring information'
                ),
                'multiOptions'  => $resourceTypes
            )
        );

        $this->addElement(
            'select',
            'resource',
            array(
                'required'      => true,
                'label'         => $this->translate('Resource'),
                'description'   => $this->translate('The resource to use'),
                'multiOptions'  => $this->resources[$resourceType],
                'value'         => current($this->resources[$resourceType]),
                'autosubmit'    => true
            )
        );
        $resourceName = isset($formData['resource']) ? $formData['resource'] : $this->getValue('resource');
        $this->addElement(
            'note',
            'resource_note',
            array(
                'escape'        => false,
                'value'         => sprintf(
                    '<a href="%1$s" data-base-target="_next" title="%2$s" aria-label="%2$s">%3$s</a>',
                    $this->getView()->url('config/editresource', array('resource' => $resourceName)),
                    sprintf($this->translate('Show the configuration of the %s resource'), $resourceName),
                    $this->translate('Show resource configuration')
                )
            )
        );

        if (isset($formData['skip_validation']) && $formData['skip_validation']) {
            // In case another error occured and the checkbox was displayed before
            $this->addSkipValidationCheckbox();
        }
    }

    /**
     * Populate the configuration of the backend to load
     */
    public function onRequest()
    {
        if ($this->backendToLoad) {
            $data = $this->config->getSection($this->backendToLoad)->toArray();
            $data['name'] = $this->backendToLoad;
            $this->populate($data);
        }
    }

    /**
     * Return whether the given values are valid
     *
     * @param   array   $formData   The data to validate
     *
     * @return  bool
     */
    public function isValid($formData)
    {
        if (! parent::isValid($formData)) {
            return false;
        }

        if (($el = $this->getElement('skip_validation')) === null || false === $el->isChecked()) {
            $resourceConfig = ResourceFactory::getResourceConfig($this->getValue('resource'));
            if (! self::isValidIdoSchema($this, $resourceConfig)
                || (! $this->getElement('disabled')->isChecked()
                    && ! self::isValidIdoInstance($this, $resourceConfig))
            ) {
                if ($el === null) {
                    $this->addSkipValidationCheckbox();
                }

                return false;
            }
        }

        return true;
    }

    /**
     * Add a checkbox to the form by which the user can skip the schema validation
     */
    protected function addSkipValidationCheckbox()
    {
        $this->addElement(
            'checkbox',
            'skip_validation',
            array(
                'order'         => 0,
                'ignore'        => true,
                'label'         => $this->translate('Skip Validation'),
                'description'   => $this->translate(
                    'Check this to not to validate the IDO schema of the chosen resource.'
                )
            )
        );
    }

    /**
     * Return whether the given resource contains a valid IDO schema
     *
     * @param   Form            $form
     * @param   ConfigObject    $resourceConfig
     *
     * @return  bool
     */
    public static function isValidIdoSchema(Form $form, ConfigObject $resourceConfig)
    {
        try {
            $db = ResourceFactory::createResource($resourceConfig);
            $db->select()->from('icinga_dbversion', array('version'))->fetchOne();
        } catch (Exception $_) {
            $form->error($form->translate(
                'Cannot find the IDO schema. Please verify that the given database '
                . 'contains the schema and that the configured user has access to it.'
            ));
            return false;
        }

        return true;
    }

    /**
     * Return whether a single icinga instance is writing to the given resource
     *
     * @param   Form            $form
     * @param   ConfigObject    $resourceConfig
     *
     * @return  bool                                True if it's a single instance, false if none
     *                                              or multiple instances are writing to it
     */
    public static function isValidIdoInstance(Form $form, ConfigObject $resourceConfig)
    {
        $db = ResourceFactory::createResource($resourceConfig);
        $rowCount = $db->select()->from('icinga_instances')->count();

        if ($rowCount === 0) {
            $form->warning($form->translate(
                'There is currently no icinga instance writing to the IDO. Make sure '
                . 'that a icinga instance is configured and able to write to the IDO.'
            ));
            return false;
        } elseif ($rowCount > 1) {
            $form->warning($form->translate(
                'There is currently more than one icinga instance writing to the IDO. You\'ll see all objects from all'
                . ' instances without any differentation. If this is not desired, consider setting up a separate IDO'
                . ' for each instance.'
            ));
            return false;
        }

        return true;
    }
}