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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
|
<?php
namespace Icinga\Module\Businessprocess;
use Exception;
use Icinga\Application\Modules\Module;
use Icinga\Exception\IcingaException;
use Icinga\Exception\NotFoundError;
use Icinga\Module\Businessprocess\Exception\NestingError;
use Icinga\Module\Businessprocess\Modification\ProcessChanges;
use Icinga\Module\Businessprocess\ProvidedHook\Icingadb\IcingadbSupport;
use Icinga\Module\Businessprocess\Storage\LegacyStorage;
use Icinga\Module\Monitoring\Backend\MonitoringBackend;
use ipl\Sql\Connection as IcingaDbConnection;
class BpConfig
{
const SOFT_STATE = 0;
const HARD_STATE = 1;
/**
* Name of the configured monitoring backend
*
* @var string
*/
protected $backendName;
/**
* Backend to retrieve states from
*
* @var MonitoringBackend|IcingaDbConnection
*/
protected $backend;
/**
* @var LegacyStorage
*/
protected $storage;
/** @var Metadata */
protected $metadata;
/**
* Business process name
*
* @var string
*/
protected $name;
/**
* Business process title
*
* @var string
*/
protected $title;
/**
* State type, soft or hard
*
* @var int
*/
protected $state_type;
/**
* Warnings, usually filled at process build time
*
* @var array
*/
protected $warnings = array();
/**
* Errors, usually filled at process build time
*
* @var array
*/
protected $errors = array();
/**
* All used node objects
*
* @var array
*/
protected $nodes = array();
/**
* Root node objects
*
* @var array
*/
protected $root_nodes = array();
/**
* Imported nodes
*
* @var ImportedNode[]
*/
protected $importedNodes = [];
/**
* Imported configs
*
* @var BpConfig[]
*/
protected $importedConfigs = [];
/**
* All host names { 'hostA' => true, ... }
*
* @var array
*/
protected $hosts = array();
/** @var bool Whether catchable errors should be thrown nonetheless */
protected $throwErrors = false;
protected $loopDetection = array();
/**
* Applied state simulation
*
* @var Simulation
*/
protected $simulation;
protected $changeCount = 0;
protected $simulationCount = 0;
/** @var ProcessChanges */
protected $appliedChanges;
public function __construct()
{
}
/**
* Retrieve metadata for this configuration
*
* @return Metadata
*/
public function getMetadata()
{
if ($this->metadata === null) {
$this->metadata = new Metadata($this->name);
}
return $this->metadata;
}
/**
* Set metadata
*
* @param Metadata $metadata
*
* @return $this
*/
public function setMetadata(Metadata $metadata)
{
$this->metadata = $metadata;
return $this;
}
/**
* Apply pending process changes
*
* @param ProcessChanges $changes
*
* @return $this
*/
public function applyChanges(ProcessChanges $changes)
{
$cnt = 0;
foreach ($changes->getChanges() as $change) {
$cnt++;
$change->applyTo($this);
}
$this->changeCount = $cnt;
$this->appliedChanges = $changes;
return $this;
}
/**
* Apply a state simulation
*
* @param Simulation $simulation
*
* @return $this
*/
public function applySimulation(Simulation $simulation)
{
$cnt = 0;
foreach ($simulation->simulations() as $node => $s) {
if (! $this->hasNode($node)) {
continue;
}
$cnt++;
$this->getNode($node)
->setState($s->state)
->setAck($s->acknowledged)
->setDowntime($s->in_downtime)
->setMissing(false);
}
$this->simulationCount = $cnt;
return $this;
}
/**
* Number of applied changes
*
* @return int
*/
public function countChanges()
{
return $this->changeCount;
}
/**
* Whether changes have been applied to this configuration
*
* @return int
*/
public function hasChanges()
{
return $this->countChanges() > 0;
}
/**
* @param $name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getHtmlId()
{
return 'businessprocess-' . preg_replace('/[\r\n\t\s]/', '_', $this->getName());
}
public function setTitle($title)
{
$this->title = $title;
return $this;
}
public function getTitle()
{
return $this->getMetadata()->getTitle();
}
public function hasTitle()
{
return $this->getMetadata()->has('Title');
}
public function getBackendName()
{
return $this->getMetadata()->get('Backend');
}
public function hasBackendName()
{
return $this->getMetadata()->has('Backend');
}
public function setBackend($backend)
{
$this->backend = $backend;
return $this;
}
public function getBackend()
{
if ($this->backend === null) {
if (Module::exists('icingadb')
&& (! $this->hasBackendName() && IcingadbSupport::useIcingaDbAsBackend())) {
$this->backend = IcingaDbObject::fetchDb();
} else {
$this->backend = MonitoringBackend::instance(
$this->getBackendName()
);
}
}
return $this->backend;
}
public function hasBackend()
{
return $this->backend !== null;
}
public function hasBeenChanged()
{
return false;
}
public function hasSimulations()
{
return $this->countSimulations() > 0;
}
public function countSimulations()
{
return $this->simulationCount;
}
public function clearAppliedChanges()
{
if ($this->appliedChanges !== null) {
$this->appliedChanges->clear();
}
return $this;
}
public function getStateType()
{
if ($this->state_type === null) {
if ($this->getMetadata()->has('Statetype')) {
switch ($this->getMetadata()->get('Statetype')) {
case 'hard':
$this->state_type = self::HARD_STATE;
break;
case 'soft':
$this->state_type = self::SOFT_STATE;
break;
}
} else {
$this->state_type = self::HARD_STATE;
}
}
return $this->state_type;
}
public function useSoftStates()
{
$this->state_type = self::SOFT_STATE;
return $this;
}
public function useHardStates()
{
$this->state_type = self::HARD_STATE;
return $this;
}
public function usesSoftStates()
{
return $this->getStateType() === self::SOFT_STATE;
}
public function usesHardStates()
{
return $this->getStateType() === self::HARD_STATE;
}
public function addRootNode($name)
{
$this->root_nodes[$name] = $this->getNode($name);
return $this;
}
public function removeRootNode($name)
{
if ($this->isRootNode($name)) {
unset($this->root_nodes[$name]);
}
return $this;
}
public function isRootNode($name)
{
return array_key_exists($name, $this->root_nodes);
}
/**
* @return BpNode[]
*/
public function getChildren()
{
return $this->getRootNodes();
}
/**
* @return int
*/
public function countChildren()
{
return count($this->root_nodes);
}
/**
* @return BpNode[]
*/
public function getRootNodes()
{
if ($this->getMetadata()->isManuallyOrdered()) {
uasort($this->root_nodes, function (BpNode $a, BpNode $b) {
$a = $a->getDisplay();
$b = $b->getDisplay();
return $a > $b ? 1 : ($a < $b ? -1 : 0);
});
} else {
ksort($this->root_nodes, SORT_NATURAL | SORT_FLAG_CASE);
}
return $this->root_nodes;
}
public function listRootNodes()
{
$names = array_keys($this->root_nodes);
if ($this->getMetadata()->isManuallyOrdered()) {
uasort($names, function ($a, $b) {
$a = $this->root_nodes[$a]->getDisplay();
$b = $this->root_nodes[$b]->getDisplay();
return $a > $b ? 1 : ($a < $b ? -1 : 0);
});
} else {
natcasesort($names);
}
return $names;
}
public function getNodes()
{
return $this->nodes;
}
public function hasNode($name)
{
if (array_key_exists($name, $this->nodes)) {
return true;
} elseif ($name[0] === '@') {
list($configName, $nodeName) = preg_split('~:\s*~', substr($name, 1), 2);
return $this->getImportedConfig($configName)->hasNode($nodeName);
}
return false;
}
public function hasRootNode($name)
{
return array_key_exists($name, $this->root_nodes);
}
public function createService($host, $service)
{
$node = new ServiceNode(
(object) array(
'hostname' => $host,
'service' => $service
)
);
$node->setBpConfig($this);
$this->nodes[$host . ';' . $service] = $node;
$this->hosts[$host] = true;
return $node;
}
public function createHost($host)
{
$node = new HostNode((object) array('hostname' => $host));
$node->setBpConfig($this);
$this->nodes[$host . ';Hoststatus'] = $node;
$this->hosts[$host] = true;
return $node;
}
public function calculateAllStates()
{
foreach ($this->getRootNodes() as $node) {
$node->getState();
}
return $this;
}
public function clearAllStates()
{
foreach ($this->getBpNodes() as $node) {
$node->clearState();
}
return $this;
}
public function listInvolvedHostNames(&$usedConfigs = null)
{
$hosts = $this->hosts;
if (! empty($this->importedNodes)) {
$usedConfigs[$this->getName()] = true;
foreach ($this->importedNodes as $node) {
if (isset($usedConfigs[$node->getConfigName()])) {
continue;
}
$hosts += array_flip($node->getBpConfig()->listInvolvedHostNames($usedConfigs));
}
}
return array_keys($hosts);
}
/**
* Create and attach a new process (BpNode)
*
* @param string $name Process name
* @param string $operator Operator (defaults to &)
*
* @return BpNode
*/
public function createBp($name, $operator = '&')
{
$node = new BpNode((object) array(
'name' => $name,
'operator' => $operator,
'child_names' => array(),
));
$node->setBpConfig($this);
$this->addNode($name, $node);
return $node;
}
public function createMissingBp($name)
{
return $this->createBp($name)->setMissing();
}
public function getMissingChildren()
{
$missing = array();
foreach ($this->getRootNodes() as $root) {
$missing += $root->getMissingChildren();
}
return $missing;
}
public function createImportedNode($config, $name = null)
{
$params = (object) array('configName' => $config);
if ($name !== null) {
$params->node = $name;
}
$node = new ImportedNode($this, $params);
$this->importedNodes[$node->getName()] = $node;
$this->nodes[$node->getName()] = $node;
return $node;
}
public function getImportedNodes()
{
return $this->importedNodes;
}
public function getImportedConfig($name)
{
if (! isset($this->importedConfigs[$name])) {
$import = $this->storage()->loadProcess($name);
if ($this->usesSoftStates()) {
$import->useSoftStates();
} else {
$import->useHardStates();
}
$this->importedConfigs[$name] = $import;
}
return $this->importedConfigs[$name];
}
public function listInvolvedConfigs(&$configs = null)
{
if ($configs === null) {
$configs[$this->getName()] = $this;
}
foreach ($this->importedNodes as $node) {
if (! isset($configs[$node->getConfigName()])) {
$config = $node->getBpConfig();
$configs[$node->getConfigName()] = $config;
$config->listInvolvedConfigs($configs);
}
}
return $configs;
}
/**
* @return LegacyStorage
*/
protected function storage()
{
if ($this->storage === null) {
$this->storage = LegacyStorage::getInstance();
}
return $this->storage;
}
/**
* @param string $name
* @return Node
* @throws Exception
*/
public function getNode($name)
{
if ($name === '__unbound__') {
return $this->getUnboundBaseNode();
}
if (array_key_exists($name, $this->nodes)) {
return $this->nodes[$name];
}
if ($name[0] === '@') {
list($configName, $nodeName) = preg_split('~:\s*~', substr($name, 1), 2);
return $this->getImportedConfig($configName)->getNode($nodeName);
}
// Fallback: if it is a service, create an empty one:
$this->warn(sprintf('The node "%s" doesn\'t exist', $name));
$pos = strpos($name, ';');
if ($pos !== false) {
$host = substr($name, 0, $pos);
$service = substr($name, $pos + 1);
// TODO: deactivated, this scares me, test it
if ($service === 'Hoststatus') {
return $this->createHost($host);
} else {
return $this->createService($host, $service);
}
}
throw new Exception(
sprintf('The node "%s" doesn\'t exist', $name)
);
}
/**
* @return BpNode
*/
public function getUnboundBaseNode()
{
// Hint: state is useless here, but triggers parent/child "calculation"
// This is an ugly workaround and should be made obsolete
$this->calculateAllStates();
$names = array_keys($this->getUnboundNodes());
$bp = new BpNode((object) array(
'name' => '__unbound__',
'operator' => '&',
'child_names' => $names
));
$bp->setBpConfig($this);
$bp->setAlias($this->translate('Unbound nodes'));
return $bp;
}
/**
* @param $name
* @return BpNode
*
* @throws NotFoundError
*/
public function getBpNode($name)
{
if ($this->hasBpNode($name)) {
return $this->nodes[$name];
} else {
throw new NotFoundError('Trying to access a missing business process node "%s"', $name);
}
}
/**
* @param $name
*
* @return bool
*/
public function hasBpNode($name)
{
return array_key_exists($name, $this->nodes)
&& $this->nodes[$name] instanceof BpNode;
}
/**
* Set the state for a specific node
*
* @param string $name Node name
* @param int $state Desired state
*
* @return $this
*/
public function setNodeState($name, $state)
{
$this->getNode($name)->setState($state);
return $this;
}
/**
* Add the given node to the given BpNode
*
* @param $name
* @param BpNode $node
*
* @return $this
*/
public function addNode($name, BpNode $node)
{
if (array_key_exists($name, $this->nodes)) {
$this->warn(
sprintf(
mt('businessprocess', 'Node "%s" has been defined twice'),
$name
)
);
}
$this->nodes[$name] = $node;
if ($node->getDisplay() > 0) {
if (! $this->isRootNode($name)) {
$this->addRootNode($name);
}
} else {
if ($this->isRootNode($name)) {
$this->removeRootNode($name);
}
}
return $this;
}
/**
* Remove all occurrences of a specific node by name
*
* @param $name
*/
public function removeNode($name)
{
unset($this->nodes[$name]);
if (array_key_exists($name, $this->root_nodes)) {
unset($this->root_nodes[$name]);
}
foreach ($this->getBpNodes() as $node) {
if ($node->hasChild($name)) {
$node->removeChild($name);
}
}
}
/**
* Get all business process nodes
*
* @return BpNode[]
*/
public function getBpNodes()
{
$nodes = array();
foreach ($this->nodes as $node) {
if ($node instanceof BpNode) {
$nodes[$node->getName()] = $node;
}
}
return $nodes;
}
/**
* List all business process node names
*
* @return array
*/
public function listBpNodes()
{
$nodes = array();
foreach ($this->getBpNodes() as $name => $node) {
$alias = $node->getAlias();
$nodes[$name] = $name === $alias ? $name : sprintf('%s (%s)', $alias, $node);
}
if ($this->getMetadata()->isManuallyOrdered()) {
uasort($nodes, function ($a, $b) {
$a = $this->nodes[$a]->getDisplay();
$b = $this->nodes[$b]->getDisplay();
return $a > $b ? 1 : ($a < $b ? -1 : 0);
});
} else {
natcasesort($nodes);
}
return $nodes;
}
/**
* All business process nodes defined in this config but not
* assigned to any parent
*
* @return BpNode[]
*/
public function getUnboundNodes()
{
$nodes = array();
foreach ($this->getBpNodes() as $name => $node) {
if ($node->hasParents()) {
continue;
}
if ($node->getDisplay() === 0) {
$nodes[$name] = $node;
}
}
return $nodes;
}
/**
* @return bool
*/
public function hasWarnings()
{
return ! empty($this->warnings);
}
/**
* @return array
*/
public function getWarnings()
{
return $this->warnings;
}
/**
* @return bool
*/
public function hasErrors()
{
return ! empty($this->errors) || $this->isEmpty();
}
/**
* @return array
*/
public function getErrors()
{
$errors = $this->errors;
if ($this->isEmpty()) {
$errors[] = sprintf(
$this->translate(
'No business process nodes for "%s" have been defined yet'
),
$this->getTitle()
);
}
return $errors;
}
/**
* Translation helper
*
* @param $msg
*
* @return mixed|string
*/
public function translate($msg)
{
return mt('businessprocess', $msg);
}
/**
* Add a message to our warning stack
*
* @param $msg
*/
protected function warn($msg)
{
$args = func_get_args();
array_shift($args);
$this->warnings[] = vsprintf($msg, $args);
}
/**
* @param string $msg,...
*
* @return $this
*
* @throws IcingaException
*/
public function addError($msg)
{
$args = func_get_args();
array_shift($args);
if (! empty($args)) {
$msg = vsprintf($msg, $args);
}
if ($this->throwErrors) {
throw new IcingaException($msg);
}
$this->errors[] = $msg;
return $this;
}
/**
* Decide whether errors should be thrown or collected
*
* @param bool $throw
*
* @return $this
*/
public function throwErrors($throw = true)
{
$this->throwErrors = $throw;
return $this;
}
/**
* Begin loop detection for the given name
*
* Will throw a NestingError in case this node will be met again below itself
*
* @param $name
*
* @throws NestingError
*/
public function beginLoopDetection($name)
{
// echo "Begin loop $name\n";
if (array_key_exists($name, $this->loopDetection)) {
$loop = array_keys($this->loopDetection);
$loop[] = $name;
$this->loopDetection = array();
throw new NestingError('Loop detected: %s', implode(' -> ', $loop));
}
$this->loopDetection[$name] = true;
}
/**
* Remove the given name from the loop detection stack
*
* @param $name
*/
public function endLoopDetection($name)
{
// echo "End loop $this->name\n";
unset($this->loopDetection[$name]);
}
/**
* Whether this configuration has any Nodes
*
* @return bool
*/
public function isEmpty()
{
// This is faster
if (! empty($this->root_nodes)) {
return false;
}
return count($this->listBpNodes()) === 0;
}
/**
* Export the config to array
*
* @param bool $flat If false, children will be added to the array key children, else the array will be flat
*
* @return array
*/
public function toArray($flat = false)
{
$data = [
'name' => $this->getTitle(),
'path' => $this->getTitle()
];
$children = [];
foreach ($this->getChildren() as $node) {
if ($flat) {
$children = array_merge($children, $node->toArray($data, $flat));
} else {
$children[] = $node->toArray($data, $flat);
}
}
if ($flat) {
$data = [$data];
if (! empty($children)) {
$data = array_merge($data, $children);
}
} else {
$data['children'] = $children;
}
return $data;
}
}
|