summaryrefslogtreecommitdiffstats
path: root/application/forms/Command/Object/ScheduleServiceDowntimeForm.php
blob: b237408ae654855fbb058b702db560eaced5c637 (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
<?php

/* Icinga DB Web | (c) 2021 Icinga GmbH | GPLv2 */

namespace Icinga\Module\Icingadb\Forms\Command\Object;

use CallbackFilterIterator;
use DateInterval;
use DateTime;
use Icinga\Application\Config;
use Icinga\Module\Icingadb\Command\Object\ScheduleServiceDowntimeCommand;
use Icinga\Module\Icingadb\Forms\Command\CommandForm;
use Icinga\Web\Notification;
use ipl\Html\Attributes;
use ipl\Html\HtmlElement;
use ipl\Html\Text;
use ipl\Orm\Model;
use ipl\Validator\CallbackValidator;
use ipl\Web\FormDecorator\IcingaFormDecorator;
use ipl\Web\Widget\Icon;
use Iterator;
use Traversable;

class ScheduleServiceDowntimeForm extends CommandForm
{
    /** @var DateTime downtime start */
    protected $start;

    /** @var DateTime fixed downtime end */
    protected $fixedEnd;

    /**@var DateTime flexible downtime end */
    protected $flexibleEnd;

    /**  @var DateInterval flexible downtime duration */
    protected $flexibleDuration;

    /** @var mixed Comment Text */
    protected $commentText;

    /**
     * Initialize this form
     */
    public function __construct()
    {
        $this->start = new DateTime();

        $config = Config::module('icingadb');

        $this->commentText = $config->get('settings', 'hostdowntime_comment_text');
        $fixedEnd = clone $this->start;
        $fixed = $config->get('settings', 'servicedowntime_end_fixed', 'PT1H');
        $this->fixedEnd = $fixedEnd->add(new DateInterval($fixed));

        $flexibleEnd = clone $this->start;
        $flexible = $config->get('settings', 'servicedowntime_end_flexible', 'PT2H');
        $this->flexibleEnd = $flexibleEnd->add(new DateInterval($flexible));

        $flexibleDuration = $config->get('settings', 'servicedowntime_flexible_duration', 'PT2H');
        $this->flexibleDuration = new DateInterval($flexibleDuration);

        $this->on(self::ON_SUCCESS, function () {
            if ($this->errorOccurred) {
                return;
            }

            $countObjects = count($this->getObjects());

            Notification::success(sprintf(
                tp('Scheduled downtime successfully', 'Scheduled downtime for %d services successfully', $countObjects),
                $countObjects
            ));
        });
    }

    protected function assembleElements()
    {
        $isFlexible = $this->getPopulatedValue('flexible') === 'y';

        $this->addHtml(new HtmlElement(
            'div',
            Attributes::create(['class' => 'form-description']),
            new Icon('info-circle', ['class' => 'form-description-icon']),
            new HtmlElement(
                'ul',
                null,
                new HtmlElement(
                    'li',
                    null,
                    Text::create(t(
                        'This command is used to schedule host and service downtimes. During the downtime specified'
                        . ' by the start and end time, Icinga will not send notifications out about the hosts and'
                        . ' services. When the scheduled downtime expires, Icinga will send out notifications for'
                        . ' the hosts and services as it normally would.'
                    ))
                )
            )
        ));

        $decorator = new IcingaFormDecorator();

        $this->addElement(
            'textarea',
            'comment',
            [
                'required'      => true,
                'label'         => t('Comment'),
                'description'   => t(
                    'If you work with other administrators, you may find it useful to share information about'
                    . ' the host or service that is having problems. Make sure you enter a brief description of'
                    . ' what you are doing.'
                ),
                'value'         => $this->commentText
            ]
        );
        $decorator->decorate($this->getElement('comment'));

        $this->addElement(
            'localDateTime',
            'start',
            [
                'data-use-datetime-picker'  => true,
                'required'                  => true,
                'value'                     => $this->start,
                'label'                     => t('Start Time'),
                'description'               => t('Set the start date and time for the downtime.')
            ]
        );
        $decorator->decorate($this->getElement('start'));

        $this->addElement(
            'localDateTime',
            'end',
            [
                'data-use-datetime-picker'  => true,
                'required'                  => true,
                'label'                     => t('End Time'),
                'description'               => t('Set the end date and time for the downtime.'),
                'value'                     => $isFlexible ? $this->flexibleEnd : $this->fixedEnd,
                'validators'                => [
                    'DateTime' => ['break_chain_on_failure' => true],
                    'Callback' => function ($value, $validator) {
                    /** @var CallbackValidator $validator */

                        if ($value <= $this->getValue('start')) {
                            $validator->addMessage(t('The end time must be greater than the start time'));
                            return false;
                        }

                        if ($value <= (new DateTime())) {
                            $validator->addMessage(t('A downtime must not be in the past'));
                            return false;
                        }

                        return true;
                    }
                ]
            ]
        );
        $decorator->decorate($this->getElement('end'));

        $this->addElement(
            'checkbox',
            'flexible',
            [
                'class'         => 'autosubmit',
                'label'         => t('Flexible'),
                'description'   => t(
                    'To make this a flexible downtime, check this option. A flexible downtime starts when the host'
                    . ' or service enters a problem state sometime between the start and end times you specified.'
                    . ' It then lasts as long as the duration time you enter.'
                )
            ]
        );
        $decorator->decorate($this->getElement('flexible'));

        if ($isFlexible) {
            $hoursInput = $this->createElement(
                'number',
                'hours',
                [
                    'required'   => true,
                    'label'      => t('Duration'),
                    'value'      => $this->flexibleDuration->h,
                    'min'        => 0,
                    'validators' => [
                        'Callback' => function ($value, $validator) {
                            /** @var CallbackValidator $validator */

                            if ($this->getValue('minutes') == 0 && $value == 0) {
                                $validator->addMessage(t('The duration must not be zero'));
                                return false;
                            }

                            return true;
                        }
                    ]
                ]
            );
            $this->registerElement($hoursInput);
            $decorator->decorate($hoursInput);

            $minutesInput = $this->createElement(
                'number',
                'minutes',
                [
                    'required'  => true,
                    'value'     => $this->flexibleDuration->m,
                    'min'       => 0
                ]
            );
            $this->registerElement($minutesInput);
            $minutesInput->addWrapper(
                new HtmlElement('label', null, new HtmlElement('span', null, Text::create(t('Minutes'))))
            );

            $hoursInput->getWrapper()->on(
                IcingaFormDecorator::ON_ASSEMBLED,
                function ($hoursInputWrapper) use ($minutesInput, $hoursInput) {
                    $hoursInputWrapper
                        ->insertAfter($minutesInput, $hoursInput)
                        ->getAttributes()->add('class', 'downtime-duration');
                }
            );

            $hoursInput->prependWrapper(
                new HtmlElement('label', null, new HtmlElement('span', null, Text::create(t('Hours'))))
            );

            $this->add($hoursInput);
        }
    }

    protected function assembleSubmitButton()
    {
        $this->addElement(
            'submit',
            'btn_submit',
            [
                'required'  => true,
                'label'     => tp('Schedule downtime', 'Schedule downtimes', count($this->getObjects()))
            ]
        );

        (new IcingaFormDecorator())->decorate($this->getElement('btn_submit'));
    }

    protected function getCommands(Iterator $objects): Traversable
    {
        $granted = new CallbackFilterIterator($objects, function (Model $object): bool {
            return $this->isGrantedOn('icingadb/command/downtime/schedule', $object);
        });

        $granted->rewind(); // Forwards the pointer to the first element
        if ($granted->valid()) {
            $command = new ScheduleServiceDowntimeCommand();
            $command->setObjects($granted);
            $command->setComment($this->getValue('comment'));
            $command->setAuthor($this->getAuth()->getUser()->getUsername());
            $command->setStart($this->getValue('start')->getTimestamp());
            $command->setEnd($this->getValue('end')->getTimestamp());

            if ($this->getElement('flexible')->isChecked()) {
                $command->setFixed(false);
                $command->setDuration(
                    $this->getValue('hours') * 3600 + $this->getValue('minutes') * 60
                );
            }

            yield $command;
        }
    }
}