summaryrefslogtreecommitdiffstats
path: root/library/Director/Objects/IcingaDependency.php
blob: abd92e6256f216bcadad005b44d7a16f6815ffaf (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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
<?php

namespace Icinga\Module\Director\Objects;

use Icinga\Exception\ConfigurationError;
use Icinga\Module\Director\DirectorObject\Automation\ExportInterface;
use Icinga\Module\Director\IcingaConfig\IcingaConfigHelper as c;
use Icinga\Exception\NotFoundError;
use Icinga\Data\Filter\Filter;

class IcingaDependency extends IcingaObject implements ExportInterface
{
    protected $table = 'icinga_dependency';

    protected $defaultProperties = [
        'id'                     => null,
        'uuid'                   => null,
        'object_name'            => null,
        'object_type'            => null,
        'disabled'               => 'n',
        'apply_to'               => null,
        'parent_host_id'         => null,
        'parent_host_var'        => null,
        'parent_service_id'      => null,
        'child_host_id'          => null,
        'child_service_id'       => null,
        'disable_checks'         => null,
        'disable_notifications'  => null,
        'ignore_soft_states'     => null,
        'period_id'              => null,
        'zone_id'                => null,
        'assign_filter'          => null,
        'parent_service_by_name' => null,
    ];

    protected $uuidColumn = 'uuid';

    protected $supportsCustomVars = false;

    protected $supportsImports = true;

    protected $supportsApplyRules = true;

    /**
     * @internal
     * @var bool
     */
    protected $renderApplyForArray = false;

    protected $relatedSets = [
        'states' => 'StateFilterSet',
    ];

    protected $relations = [
        'zone'           => 'IcingaZone',
        'parent_host'    => 'IcingaHost',
        'parent_service' => 'IcingaService',
        'child_host'     => 'IcingaHost',
        'child_service'  => 'IcingaService',
        'period'         => 'IcingaTimePeriod',
    ];

    protected $booleans = [
        'disable_checks'        => 'disable_checks',
        'disable_notifications' => 'disable_notifications',
        'ignore_soft_states'    => 'ignore_soft_states'
    ];

    protected $propertiesNotForRendering = [
        'id',
        'object_name',
        'object_type',
        'apply_to',
    ];

    public function getUniqueIdentifier()
    {
        return $this->getObjectName();
    }

    public function parentHostIsVar()
    {
        return $this->get('parent_host_var') !== null;
    }

    /**
     * Check if the given string is a custom variable
     *
     * @param $string string
     *
     * @return false|int
     */
    protected function isCustomVar(string $string)
    {
        return preg_match('/^(?:host|service)\.vars\..+$/', $string);
    }

    /**
     * @return string
     * @throws ConfigurationError
     */
    protected function renderObjectHeader()
    {
        if ($this->isApplyRule()) {
            if (($to = $this->get('apply_to')) === null) {
                throw new ConfigurationError(
                    'Applied dependency "%s" has no valid object type',
                    $this->getObjectName()
                );
            }

            if ($this->renderApplyForArray) {
                return $this->renderArrayObjectHeader($to);
            }

            return $this->renderSingleObjectHeader($to);
        }

        return parent::renderObjectHeader();
    }

    protected function renderSingleObjectHeader($to)
    {
        return sprintf(
            "%s %s %s to %s {\n",
            $this->getObjectTypeName(),
            $this->getType(),
            c::renderString($this->getObjectName()),
            ucfirst($to)
        );
    }

    protected function renderArrayObjectHeader($to)
    {
        return sprintf(
            "%s %s %s for (host_parent_name in %s) to %s {\n",
            $this->getObjectTypeName(),
            $this->getType(),
            c::renderString($this->getObjectName()),
            $this->get('parent_host_var'),
            ucfirst($to)
        );
    }

    /**
     * @return string
     */
    protected function renderSuffix()
    {
        if (! $this->parentHostIsVar()) {
            return parent::renderSuffix();
        }

        if ((string) $this->get('assign_filter') !== '') {
            $suffix = parent::renderSuffix();
        } else {
            $suffix = '    assign where ' . $this->renderAssignFilterExtension('')
                . "\n" . parent::renderSuffix();
        }

        if ($this->renderApplyForArray) {
            return $suffix;
        }

        return $suffix . $this->renderApplyForArrayClone();
    }

    protected function renderApplyForArrayClone()
    {
        $clone = clone($this);
        $clone->renderApplyForArray = true;

        return $clone->toConfigString();
    }

    public function isApplyForArrayClone()
    {
        return $this->renderApplyForArray;
    }

    /**
     * @codingStandardsIgnoreStart
     */
    public function renderAssign_Filter()
    {
        if ($this->parentHostIsVar()) {
            return preg_replace(
                '/\n$/m',
                $this->renderAssignFilterExtension() . "\n",
                parent::renderAssign_Filter()
            );
        }

        return parent::renderAssign_Filter();
    }

    protected function renderAssignFilterExtension($pre = ' && ')
    {
        $varName = $this->get('parent_host_var');
        if ($this->renderApplyForArray) {
            return sprintf('%stypeof(%s) == Array', $pre, $varName);
        }

        return sprintf('%stypeof(%s) == String', $pre, $varName);
    }

    protected function setKey($key)
    {
        // TODO: Check if this method can be removed
        if (is_int($key)) {
            $this->id = $key;
        } elseif (is_array($key)) {
            $keys = [
                'id',
                'parent_host_id',
                'parent_service_id',
                'child_host_id',
                'child_service_id',
                'object_name'
            ];

            foreach ($keys as $k) {
                if (array_key_exists($k, $key)) {
                    $this->set($k, $key[$k]);
                }
            }
        } else {
            return parent::setKey($key);
        }

        return $this;
    }

    protected function renderAssignments()
    {
        // TODO: this will never be reached
        if ($this->hasBeenAssignedToServiceApply()) {
            /** @var IcingaService $tmpService */
            $tmpService = $this->getRelatedObject(
                'child_service',
                $this->get('child_service_id')
            );
            // TODO: fix this, will crash:
            $assigns = $tmpService->assignments()->toConfigString();

            $filter = sprintf(
                '%s && service.name == "%s"',
                trim($assigns),
                $this->get('child_service')
            );
            return "\n    " . $filter . "\n";
        }

        if ($this->hasBeenAssignedToHostTemplateService()) {
            $filter = sprintf(
                'assign where "%s" in host.templates && service.name == "%s"',
                $this->get('child_host'),
                $this->get('child_service')
            );
            return "\n    " . $filter . "\n";
        }
        if ($this->hasBeenAssignedToHostTemplate()) {
            $filter = sprintf(
                'assign where "%s" in host.templates',
                $this->get('child_host')
            );
            return "\n    " . $filter . "\n";
        }

        if ($this->hasBeenAssignedToServiceTemplate()) {
            $filter = sprintf(
                'assign where "%s" in service.templates',
                $this->get('child_service')
            );
            return "\n    " . $filter . "\n";
        }

        return parent::renderAssignments();
    }

    protected function hasBeenAssignedToHostTemplate()
    {
        try {
            $id = $this->get('child_host_id');
            return $id && $this->getRelatedObject(
                'child_host',
                $id
            )->isTemplate();
        } catch (NotFoundError $e) {
            return false;
        }
    }

    protected function hasBeenAssignedToServiceTemplate()
    {
        try {
            $id = $this->get('child_service_id');
            return $id && $this->getRelatedObject(
                'child_service',
                $id
            )->isTemplate();
        } catch (NotFoundError $e) {
            return false;
        }
    }

    protected function hasBeenAssignedToHostTemplateService()
    {
        if (!$this->hasBeenAssignedToHostTemplate()) {
            return false;
        }
        try {
            $id = $this->get('child_service_id');
            return $id && $this->getRelatedObject(
                'child_service',
                $id
            )->isObject();
        } catch (NotFoundError $e) {
            return false;
        }
    }

    protected function hasBeenAssignedToServiceApply()
    {
        try {
            $id = $this->get('child_service_id');
            return $id && $this->getRelatedObject(
                'child_service',
                $id
            )->isApplyRule();
        } catch (NotFoundError $e) {
            return false;
        }
    }

    /**
     * Render child_host_id as host_name
     *
     * Avoid complaints for method names with underscore:
     * @codingStandardsIgnoreStart
     *
     * @return string
     */
    public function renderChild_host_id()
    {
        // @codingStandardsIgnoreEnd

        if ($this->hasBeenAssignedToHostTemplate()) {
            return '';
        }

        return $this->renderRelationProperty(
            'child_host',
            $this->get('child_host_id'),
            'child_host_name'
        );
    }

    /**
     * Render parent_host_id as parent_host_name
     *
     * Avoid complaints for method names with underscore:
     * @codingStandardsIgnoreStart
     *
     * @return string
     */
    public function renderParent_host_id()
    {
        // @codingStandardsIgnoreEnd
        return $this->renderRelationProperty(
            'parent_host',
            $this->get('parent_host_id'),
            'parent_host_name'
        );
    }

    /**
     * Render parent_host_var as parent_host
     * @codingStandardsIgnoreStart
     *
     * @return string
     */
    public function renderParent_host_var()
    {
        // @codingStandardsIgnoreEnd
        if ($this->renderApplyForArray) {
            return c::renderKeyValue(
                'parent_host_name',
                'host_parent_name'
            );
        }

        // @codingStandardsIgnoreEnd
        return c::renderKeyValue(
            'parent_host_name',
            $this->get('parent_host_var')
        );
    }

    /**
     * Render child_service_id as host_name
     *
     * Avoid complaints for method names with underscore:
     * @codingStandardsIgnoreStart
     *
     * @return string
     */
    public function renderChild_service_id()
    {
        // @codingStandardsIgnoreEnd
        if ($this->hasBeenAssignedToServiceTemplate()
            || $this->hasBeenAssignedToHostTemplateService()
            || $this->hasBeenAssignedToServiceApply()
        ) {
            return '';
        }

        return $this->renderRelationProperty(
            'child_service',
            $this->get('child_service_id'),
            'child_service_name'
        );
    }

    /**
     * Render parent_service_id as parent_service_name
     *
     * Avoid complaints for method names with underscore:
     * @codingStandardsIgnoreStart
     *
     * @return string
     */
    public function renderParent_service_id()
    {
        return $this->renderRelationProperty(
            'parent_service',
            $this->get('parent_service_id'),
            'parent_service_name'
        );
    }

    //
    /**
     * Render parent_service_by_name as parent_service_name
     *
     * Special case for parent service set as plain string for Apply rules
     *
     * @codingStandardsIgnoreStart
     *
     * @return string
     */
    public function renderParent_service_by_name()
    {
        // @codingStandardsIgnoreEnd
        $var = $this->get('parent_service_by_name');
        if ($this->isCustomVar($var)) {
            return c::renderKeyValue(
                'parent_service_name',
                $var
            );
        }
        return c::renderKeyValue(
            'parent_service_name',
            c::renderString($var)
        );
    }

    public function isApplyRule()
    {
        if ($this->hasBeenAssignedToHostTemplate()
            || $this->hasBeenAssignedToServiceTemplate()
            || $this->hasBeenAssignedToServiceApply()
        ) {
            return true;
        }

        return parent::isApplyRule();
    }

    protected function resolveUnresolvedRelatedProperty($name)
    {
        $short = substr($name, 0, -3);
        /** @var IcingaObject|string $class */
        $class = $this->getRelationClass($short);
        $objKey = $this->unresolvedRelatedProperties[$name];

        # related services need array key
        if ($class === IcingaService::class) {
            if ($name === 'parent_service_id' && $this->get('object_type') === 'apply') {
                //special case , parent service can be set as simple string for Apply
                if ($this->properties['parent_host_id'] === null) {
                    $this->reallySet(
                        'parent_service_by_name',
                        $this->unresolvedRelatedProperties[$name]
                    );
                    $this->reallySet('parent_service_id', null);
                    unset($this->unresolvedRelatedProperties[$name]);
                    return;
                }
            }

            $this->reallySet('parent_service_by_name', null);
            $hostIdProperty = str_replace('service', 'host', $name);
            if (isset($this->properties[$hostIdProperty])) {
                $objKey = [
                    'host_id'     => $this->properties[$hostIdProperty],
                    'object_name' => $this->unresolvedRelatedProperties[$name]
                ];
            } else {
                $objKey = [
                    'host_id'     => null,
                    'object_name' => $this->unresolvedRelatedProperties[$name]
                ];
            }

            try {
                $class::load($objKey, $this->connection);
            } catch (NotFoundError $e) {
                // Not a simple service on host
                // Hunt through inherited services, use service assigned to
                // template if found
                $tmpHost = IcingaHost::loadWithAutoIncId(
                    $this->properties[$hostIdProperty],
                    $this->connection
                );

                // services for applicable templates
                $resolver = $tmpHost->templateResolver();
                foreach ($resolver->fetchResolvedParents() as $template_obj) {
                    $objKey = [
                        'host_id'     => $template_obj->id,
                        'object_name' => $this->unresolvedRelatedProperties[$name]
                    ];
                    try {
                        $object = $class::load($objKey, $this->connection);
                    } catch (NotFoundError $e) {
                        continue;
                    }
                    break;
                }

                if (!isset($object)) {
                    // Not an inherited service, now try apply rules
                    $matcher = HostApplyMatches::prepare($tmpHost);
                    foreach ($this->getAllApplyRules() as $rule) {
                        if ($matcher->matchesFilter($rule->filter)) {
                            if ($rule->name === $this->unresolvedRelatedProperties[$name]) {
                                $object = IcingaService::loadWithAutoIncId(
                                    $rule->id,
                                    $this->connection
                                );
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            $object = $class::load($objKey, $this->connection);
        }

        if (isset($object)) {
            $this->reallySet($name, $object->get('id'));
            unset($this->unresolvedRelatedProperties[$name]);
        } else {
            // Depend on a single service on a single host. Rare case, as usually you want to
            // depend on a service on the very same host - and leave the Host field empty. The
            // latter is already being handled above. This duplicates some code, but I'll leave
            // it this way for now. There might have been a reason for the parent_host_id = null
            // check in that code.
            if ($name === 'parent_service_id' && $this->get('object_type') === 'apply') {
                $this->reallySet(
                    'parent_service_by_name',
                    $this->unresolvedRelatedProperties[$name]
                );
                $this->reallySet('parent_service_id', null);
                unset($this->unresolvedRelatedProperties[$name]);
                return;
            }
            throw new NotFoundError(sprintf(
                'Unable to resolve related property: %s "%s"',
                $name,
                $this->unresolvedRelatedProperties[$name]
            ));
        }
    }

    protected function getAllApplyRules()
    {
        $allApplyRules = $this->fetchAllApplyRules();
        foreach ($allApplyRules as $rule) {
            $rule->filter = Filter::fromQueryString($rule->assign_filter);
        }

        return $allApplyRules;
    }

    protected function fetchAllApplyRules()
    {
        $db = $this->connection->getDbAdapter();
        $query = $db->select()->from(['s' => 'icinga_service'], [
            'id'            => 's.id',
            'name'          => 's.object_name',
            'assign_filter' => 's.assign_filter',
        ])->where('object_type = ? AND assign_filter IS NOT NULL', 'apply');

        return $db->fetchAll($query);
    }

    protected function getRelatedProperty($key)
    {
        $related = parent::getRelatedProperty($key);
        // handle special case for plain string parent service on Dependency
        // Apply rules
        if ($related === null
            && $key === 'parent_service'
            && (
                $this->get('parent_service_by_name')
                && ! $this->isCustomVar($this->get('parent_service_by_name'))
            )
        ) {
            return $this->get('parent_service_by_name');
        }

        return $related;
    }
}