summaryrefslogtreecommitdiffstats
path: root/library/Icingadb/Common/ObjectInspectionDetail.php
blob: b30797b4ebecb6aff425763f4bc58a21f79e7b68 (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
<?php

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

namespace Icinga\Module\Icingadb\Common;

use DateTime;
use DateTimeZone;
use Exception;
use Icinga\Exception\IcingaException;
use Icinga\Exception\Json\JsonDecodeException;
use Icinga\Module\Icingadb\Model\Host;
use Icinga\Module\Icingadb\Model\Service;
use Icinga\Module\Icingadb\Widget\Detail\CustomVarTable;
use Icinga\Util\Format;
use Icinga\Util\Json;
use InvalidArgumentException;
use ipl\Html\BaseHtmlElement;
use ipl\Html\FormattedString;
use ipl\Html\HtmlElement;
use ipl\Html\Table;
use ipl\Html\Text;
use ipl\Orm\Model;
use ipl\Web\Widget\CopyToClipboard;
use ipl\Web\Widget\EmptyState;

abstract class ObjectInspectionDetail extends BaseHtmlElement
{
    protected $tag = 'div';

    protected $defaultAttributes = ['class' => ['object-detail', 'inspection-detail']];

    /** @var Model */
    protected $object;

    /** @var array */
    protected $attrs;

    /** @var array */
    protected $joins;

    public function __construct(Model $object, array $apiResult)
    {
        $this->object = $object;
        $this->attrs = $apiResult['attrs'];
        $this->joins = $apiResult['joins'];
    }

    /**
     * Render the object source location
     *
     * @return ?array
     */
    protected function createSourceLocation()
    {
        if (! isset($this->attrs['source_location'])) {
            return;
        }

        return [
            new HtmlElement('h2', null, Text::create(t('Source Location'))),
            FormattedString::create(
                t('You can find this object in %s on line %s.'),
                new HtmlElement('strong', null, Text::create($this->attrs['source_location']['path'])),
                new HtmlElement('strong', null, Text::create($this->attrs['source_location']['first_line']))
            )
        ];
    }

    /**
     * Render object's last check result
     *
     * @return ?array
     */
    protected function createLastCheckResult()
    {
        if (! isset($this->attrs['last_check_result'])) {
            return;
        }

        $command = $this->attrs['last_check_result']['command'];
        if (is_array($command)) {
            $command = join(' ', array_map('escapeshellarg', $command));
        }

        $denylist = [
            'command',
            'output',
            'type',
            'active'
        ];

        if ($command) {
            $execCommand = new HtmlElement('pre', null, Text::create($command));
            CopyToClipboard::attachTo($execCommand);
        } else {
            $execCommand = new EmptyState(t('n. a.'));
        }

        return [
            new HtmlElement('h2', null, Text::create(t('Executed Command'))),
            $execCommand,
            new HtmlElement('h2', null, Text::create(t('Execution Details'))),
            $this->createNameValueTable(
                array_diff_key($this->attrs['last_check_result'], array_flip($denylist)),
                [
                    'execution_end'     => [$this, 'formatTimestamp'],
                    'execution_start'   => [$this, 'formatTimestamp'],
                    'schedule_end'      => [$this, 'formatTimestamp'],
                    'schedule_start'    => [$this, 'formatTimestamp'],
                    'ttl'               => [$this, 'formatSeconds'],
                    'state'             => [$this, 'formatState']
                ]
            )
        ];
    }

    protected function createRedisInfo(): array
    {
        $title = new HtmlElement('h2', null, Text::create(t('Volatile State Details')));

        try {
            $json = IcingaRedis::instance()->getConnection()
                ->hGet("icinga:{$this->object->getTableName()}:state", bin2hex($this->object->id));
        } catch (Exception $e) {
            return [$title, sprintf('Failed to load redis data: %s', $e->getMessage())];
        }

        if (! $json) {
            return [$title, new EmptyState(t('No data available in redis'))];
        }

        try {
            $data = Json::decode($json, true);
        } catch (JsonDecodeException $e) {
            return [$title, sprintf('Failed to decode redis data: %s', $e->getMessage())];
        }

        $denylist = [
            'commandline',
            'environment_id',
            'id'
        ];

        return [$title, $this->createNameValueTable(
            array_diff_key($data, array_flip($denylist)),
            [
                'last_state_change'     => [$this, 'formatMillisecondTimestamp'],
                'last_update'           => [$this, 'formatMillisecondTimestamp'],
                'next_check'            => [$this, 'formatMillisecondTimestamp'],
                'next_update'           => [$this, 'formatMillisecondTimestamp'],
                'check_timeout'         => [$this, 'formatMilliseconds'],
                'execution_time'        => [$this, 'formatMilliseconds'],
                'latency'               => [$this, 'formatMilliseconds'],
                'hard_state'            => [$this, 'formatState'],
                'previous_soft_state'   => [$this, 'formatState'],
                'previous_hard_state'   => [$this, 'formatState'],
                'state'                 => [$this, 'formatState']
            ]
        )];
    }

    protected function createAttributes(): array
    {
        $denylist = [
            'name',
            '__name',
            'host_name',
            'display_name',
            'last_check_result',
            'source_location',
            'templates',
            'package',
            'version',
            'type',
            'active',
            'paused',
            'ha_mode'
        ];

        return [
            new HtmlElement('h2', null, Text::create(t('Object Attributes'))),
            $this->createNameValueTable(
                array_diff_key($this->attrs, array_flip($denylist)),
                [
                    'acknowledgement_expiry'        => [$this, 'formatTimestamp'],
                    'acknowledgement_last_change'   => [$this, 'formatTimestamp'],
                    'check_timeout'                 => [$this, 'formatSeconds'],
                    'flapping_last_change'          => [$this, 'formatTimestamp'],
                    'last_check'                    => [$this, 'formatTimestamp'],
                    'last_hard_state_change'        => [$this, 'formatTimestamp'],
                    'last_state_change'             => [$this, 'formatTimestamp'],
                    'last_state_ok'                 => [$this, 'formatTimestamp'],
                    'last_state_up'                 => [$this, 'formatTimestamp'],
                    'last_state_warning'            => [$this, 'formatTimestamp'],
                    'last_state_critical'           => [$this, 'formatTimestamp'],
                    'last_state_down'               => [$this, 'formatTimestamp'],
                    'last_state_unknown'            => [$this, 'formatTimestamp'],
                    'last_state_unreachable'        => [$this, 'formatTimestamp'],
                    'next_check'                    => [$this, 'formatTimestamp'],
                    'next_update'                   => [$this, 'formatTimestamp'],
                    'previous_state_change'         => [$this, 'formatTimestamp'],
                    'check_interval'                => [$this, 'formatSeconds'],
                    'retry_interval'                => [$this, 'formatSeconds'],
                    'last_hard_state'               => [$this, 'formatState'],
                    'last_state'                    => [$this, 'formatState'],
                    'state'                         => [$this, 'formatState']
                ]
            )
        ];
    }

    protected function createCustomVariables()
    {
        $query = $this->object->customvar
            ->columns(['name', 'value']);

        $result = [];
        foreach ($query as $row) {
            $result[$row->name] = json_decode($row->value, true) ?? $row->value;
        }

        if (! empty($result)) {
            $vars = new CustomVarTable($result);
        } else {
            $vars = new EmptyState(t('No custom variables configured.'));
        }

        return [
            new HtmlElement('h2', null, Text::create(t('Custom Variables'))),
            $vars
        ];
    }

    /**
     * Format the given value as a json
     *
     * @param  mixed $json
     *
     * @return BaseHtmlElement|string
     */
    private function formatJson($json)
    {
        if (is_scalar($json)) {
            return Json::encode($json, JSON_UNESCAPED_SLASHES);
        }

        return new HtmlElement(
            'pre',
            null,
            Text::create(Json::encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))
        );
    }

    /**
     * Format the given timestamp
     *
     * @param int|float|null $ts
     *
     * @return EmptyState|string
     */
    private function formatTimestamp($ts)
    {
        if (empty($ts)) {
            return new EmptyState(t('n. a.'));
        }

        if (is_float($ts)) {
            $dt = DateTime::createFromFormat('U.u', sprintf('%F', $ts));
        } else {
            $dt = (new DateTime())->setTimestamp($ts);
        }

        return $dt->setTimezone(new DateTimeZone('UTC'))
            ->format('Y-m-d\TH:i:s.vP');
    }

    /**
     * Format the given timestamp (in milliseconds)
     *
     * @param int|float|null $ms
     *
     * @return EmptyState|string
     */
    private function formatMillisecondTimestamp($ms)
    {
        return $this->formatTimestamp($ms / 1000.0);
    }

    private function formatSeconds($s): string
    {
        return Format::seconds($s);
    }

    private function formatMilliseconds($ms): string
    {
        return Format::seconds($ms / 1000.0);
    }

    private function formatState(int $state)
    {
        try {
            switch (true) {
                case $this->object instanceof Host:
                    return HostStates::text($state);
                case $this->object instanceof Service:
                    return ServiceStates::text($state);
                default:
                    return $state;
            }
        } catch (InvalidArgumentException $_) {
            // The Icinga 2 API sometimes delivers strange details
            return (string) $state;
        }
    }

    private function createNameValueTable(array $data, array $formatters): Table
    {
        $table = new Table();
        $table->addAttributes(['class' => 'name-value-table']);
        foreach ($data as $name => $value) {
            if (empty($value) && ($value === null || is_string($value) || is_array($value))) {
                $value = new EmptyState(t('n. a.'));
            } else {
                try {
                    if (isset($formatters[$name])) {
                        $value = call_user_func($formatters[$name], $value);
                    } else {
                        $value = $this->formatJson($value);

                        if ($value instanceof BaseHtmlElement) {
                            CopyToClipboard::attachTo($value);
                        }
                    }
                } catch (Exception $e) {
                    $value = new EmptyState(IcingaException::describe($e));
                }
            }

            $table->addHtml(Table::tr([
                Table::th($name),
                Table::td($value)
            ]));
        }

        return $table;
    }
}