summaryrefslogtreecommitdiffstats
path: root/modules/monitoring/application/forms/Config/TransportConfigForm.php
blob: c68e63dbfdfa6a3032655bac1c0c4caf57735119 (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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
<?php
/* Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

namespace Icinga\Module\Monitoring\Forms\Config;

use Icinga\Data\ConfigObject;
use Icinga\Module\Monitoring\Command\Transport\CommandTransport;
use Icinga\Module\Monitoring\Exception\CommandTransportException;
use InvalidArgumentException;
use Icinga\Application\Platform;
use Icinga\Exception\IcingaException;
use Icinga\Exception\NotFoundError;
use Icinga\Forms\ConfigForm;
use Icinga\Module\Monitoring\Command\Transport\ApiCommandTransport;
use Icinga\Module\Monitoring\Command\Transport\LocalCommandFile;
use Icinga\Module\Monitoring\Command\Transport\RemoteCommandFile;
use Icinga\Module\Monitoring\Forms\Config\Transport\ApiTransportForm;
use Icinga\Module\Monitoring\Forms\Config\Transport\LocalTransportForm;
use Icinga\Module\Monitoring\Forms\Config\Transport\RemoteTransportForm;

/**
 * Form for managing command transports
 */
class TransportConfigForm extends ConfigForm
{
    /**
     * The transport to load when displaying the form for the first time
     *
     * @var string
     */
    protected $transportToLoad;

    /**
     * The names of all available Icinga instances
     *
     * @var array
     */
    protected $instanceNames;

    /**
     * @var bool
     */
    protected $validatePartial = true;

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

    /**
     * Set the names of all available Icinga instances
     *
     * @param   array   $names
     *
     * @return  $this
     */
    public function setInstanceNames(array $names)
    {
        $this->instanceNames = $names;
        return $this;
    }

    /**
     * Return the names of all available Icinga instances
     *
     * @return  array
     */
    public function getInstanceNames()
    {
        return $this->instanceNames ?: array();
    }

    /**
     * Return a form object for the given transport type
     *
     * @param   string  $type               The transport type for which to return a form
     *
     * @return  \Icinga\Web\Form
     *
     * @throws  InvalidArgumentException    In case the given transport type is invalid
     */
    public function getTransportForm($type)
    {
        switch (strtolower($type)) {
            case LocalCommandFile::TRANSPORT:
                return new LocalTransportForm();
            case RemoteCommandFile::TRANSPORT:
                return new RemoteTransportForm();
            case ApiCommandTransport::TRANSPORT:
                return new ApiTransportForm();
            default:
                throw new InvalidArgumentException(
                    sprintf($this->translate('Invalid command transport type "%s" given'), $type)
                );
        }
    }

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

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

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

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

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

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

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

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

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

    /**
     * Remove a command transport
     *
     * @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)
    {
        $instanceNames = $this->getInstanceNames();
        if (count($instanceNames) > 1) {
            $options = array('none' => $this->translate('None', 'command transport instance association'));
            $this->addElement(
                'select',
                'instance',
                array(
                    'label'         => $this->translate('Instance Link'),
                    'description'   => $this->translate(
                        'The name of the Icinga instance this transport should exclusively transfer commands to.'
                    ),
                    'multiOptions'  => array_merge($options, array_combine($instanceNames, $instanceNames))
                )
            );
        }

        $this->addElement(
            'text',
            'name',
            array(
                'required'      => true,
                'label'         => $this->translate('Transport Name'),
                'description'   => $this->translate(
                    'The name of this command transport that is used to differentiate it from others'
                )
            )
        );

        $transportTypes = array(
            ApiCommandTransport::TRANSPORT  => $this->translate('Icinga 2 API'),
            LocalCommandFile::TRANSPORT     => $this->translate('Local Command File'),
            RemoteCommandFile::TRANSPORT    => $this->translate('Remote Command File')
        );
        if (! Platform::extensionLoaded('curl')) {
            unset($transportTypes[ApiCommandTransport::TRANSPORT]);
        }

        $transportType = isset($formData['transport']) ? $formData['transport'] : null;
        if ($transportType === null) {
            $transportType = key($transportTypes);
        }

        $this->addElements(array(
            array(
                'select',
                'transport',
                array(
                    'required'      => true,
                    'autosubmit'    => true,
                    'label'         => $this->translate('Transport Type'),
                    'multiOptions'  => $transportTypes
                )
            )
        ));

        $this->addSubForm($this->getTransportForm($transportType)->create($formData), 'transport_form');
    }

    /**
     * Add a submit button to this form and one to manually validate the configuration
     *
     * Calls parent::addSubmitButton() to add the submit button.
     *
     * @return  $this
     */
    public function addSubmitButton()
    {
        parent::addSubmitButton();

        if ($this->getSubForm('transport_form') instanceof ApiTransportForm) {
            $btnSubmit = $this->getElement('btn_submit');

            if ($btnSubmit !== null) {
                // In the setup wizard $this is being used as a subform which doesn't have a submit button.
                $this->addElement(
                    'submit',
                    'transport_validation',
                    array(
                        'ignore' => true,
                        'label' => $this->translate('Validate Configuration'),
                        'data-progress-label' => $this->translate('Validation In Progress'),
                        'decorators' => array('ViewHelper')
                    )
                );

                $this->setAttrib('data-progress-element', 'transport-progress');
                $this->addElement(
                    'note',
                    'transport-progress',
                    array(
                        'decorators' => array(
                            'ViewHelper',
                            array('Spinner', array('id' => 'transport-progress'))
                        )
                    )
                );

                $elements = array('transport_validation', 'transport-progress');

                $btnSubmit->setDecorators(array('ViewHelper'));
                array_unshift($elements, 'btn_submit');

                $this->addDisplayGroup(
                    $elements,
                    'submit_validation',
                    array(
                        'decorators' => array(
                            'FormElements',
                            array('HtmlTag', array('tag' => 'div', 'class' => 'control-group form-controls'))
                        )
                    )
                );
            }
        }

        return $this;
    }

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

    /**
     * {@inheritdoc}
     */
    public function isValidPartial(array $formData)
    {
        $isValidPartial =  parent::isValidPartial($formData);

        $transportValidation = $this->getElement('transport_validation');
        if ($transportValidation !== null && $transportValidation->isChecked() && $this->isValid($formData)) {
            $this->info($this->translate('The configuration has been successfully validated.'));
        }

        return $isValidPartial;
    }

    /**
     * {@inheritdoc}
     */
    public function isValid($formData)
    {
        if (! parent::isValid($formData)) {
            return false;
        }

        if ($this->getSubForm('transport_form') instanceof ApiTransportForm) {
            if (! isset($formData['transport_validation'])
                && isset($formData['force_creation']) && $formData['force_creation']
            ) {
                // ignore any validation result
                return true;
            }

            try {
                CommandTransport::createTransport(new ConfigObject($this->getValues()))->probe();
            } catch (CommandTransportException $e) {
                $this->error(sprintf(
                    $this->translate('Failed to successfully validate the configuration: %s'),
                    $e->getMessage()
                ));

                $this->addElement(
                    'checkbox',
                    'force_creation',
                    array(
                        'order'         => 0,
                        'ignore'        => true,
                        'label'         => $this->translate('Force Changes'),
                        'description'   => $this->translate(
                            'Check this box to enforce changes without connectivity validation'
                        )
                    )
                );

                return false;
            }
        }

        return true;
    }
}