-
Notifications
You must be signed in to change notification settings - Fork 73
/
GlobalBackendmklivestatus.php
1576 lines (1427 loc) · 59.8 KB
/
GlobalBackendmklivestatus.php
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
<?php
/*****************************************************************************
*
* GlobalBackendmklivestatus.php
*
* Backend class for handling object and state information using the
* livestatus NEB module. For mor information about CheckMK's Livestatus
* Module please visit: http://mathias-kettner.de/checkmk_livestatus.html
*
* Copyright (c) 2010 NagVis Project (Contact: info@nagvis.org),
* Mathias Kettner (Contact: mk@mathias-kettner.de)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
/**
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*
* For mor information about CheckMK's Livestatus Module
* please visit: http://mathias-kettner.de/checkmk_livestatus.html
*/
class GlobalBackendmklivestatus implements GlobalBackendInterface {
private $backendId = '';
private $CONNECT_EXC = null;
private $SOCKET = null;
private $socketType = '';
private $socketPath = '';
private $socketAddress = '';
private $socketPort = 0;
// These are the backend local configuration options
private static $validConfig = Array(
'socket' => Array(
'must' => 1,
'editable' => 1,
'default' => 'unix:/usr/local/nagios/var/rw/live',
'match' => MATCH_SOCKET,
),
'timeout' => Array(
'must' => 1,
'editable' => 1,
'default' => 5,
'match' => MATCH_INTEGER,
),
'keepalive' => Array(
'must' => 0,
'editable' => 1,
'default' => 1,
'field_type' => 'boolean',
'match' => MATCH_BOOLEAN
),
);
/**
* PUBLIC class constructor
*
* @param String ID if the backend
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
public function __construct($backendId) {
$this->backendId = $backendId;
// Parse the socket params
$this->parseSocket(cfg('backend_'.$backendId, 'socket'));
// Run preflight checks
if($this->socketType == 'unix' && !$this->checkSocketExists()) {
throw new BackendConnectionProblem(l('Unable to connect to livestatus socket. The socket [SOCKET] in backend [BACKENDID] does not exist. Maybe Nagios is not running or restarting.',
Array('BACKENDID' => $this->backendId, 'SOCKET' => $this->socketPath)));
}
if(!function_exists('fsockopen')) {
throw new BackendConnectionProblem(l('The PHP function fsockopen is not available. Needed by backend [BACKENDID].',
Array('BACKENDID' => $this->backendId, 'SOCKET' => $this->socketPath)));
}
return true;
}
/**
* PUBLIC class destructor
*
* The descrutcor closes the socket when some is open
* at the moment when the class is destroyed. It is
* important to close the socket in a clean way.
*
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
public function __destruct() {
if($this->SOCKET !== null) {
fclose($this->SOCKET);
$this->SOCKET = null;
}
}
/**
* PRIVATE parseSocket
*
* Parses and sets the socket options
*
* @return String Parses the socket
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function parseSocket($socket) {
// Explode the given socket definition
list($type, $address) = explode(':', $socket, 2);
if($type === 'unix') {
$this->socketType = $type;
$this->socketPath = $address;
} elseif($type === 'tcp') {
$this->socketType = $type;
// Extract address and port
list($address, $port) = explode(':', $address, 2);
$this->socketAddress = $address;
$this->socketPort = $port;
} else {
throw new BackendConnectionProblem(
l('Unknown socket type given in backend [BACKENDID]',
Array('BACKENDID' => $this->backendId)));
}
}
/**
* PUBLIC getValidConfig
*
* Returns the valid config for this backend
*
* @return Array
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
public static function getValidConfig() {
return self::$validConfig;
}
/**
* PRIVATE checkSocketExists()
*
* Checks if the socket exists
*
* @return Boolean
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function checkSocketExists() {
return file_exists($this->socketPath);
}
/**
* PRIVATE connectSocket()
*
* Connects to the livestatus socket when no connection is open
*
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function connectSocket() {
// Only try to connect once per page. Re-raise the connection exception on
// later tries to connect
if($this->CONNECT_EXC != null)
throw $this->CONNECT_EXC;
// Connect to the socket
// don't want to see the connection error messages - want to handle the
// errors later with an own error message
// FIXME: Maybe use pfsockopen in the future to use persistent connections
if($this->socketType === 'unix') {
$oldLevel = error_reporting(0);
$this->SOCKET = fsockopen('unix://'.$this->socketPath, NULL, $errno, $errstr, (float) cfg('backend_'.$this->backendId, 'timeout'));
error_reporting($oldLevel);
} elseif($this->socketType === 'tcp') {
$oldLevel = error_reporting(0);
$this->SOCKET = fsockopen($this->socketAddress, $this->socketPort, $errno, $errstr, (float) cfg('backend_'.$this->backendId, 'timeout'));
error_reporting($oldLevel);
}
if(!$this->SOCKET) {
$this->SOCKET = null;
$this->CONNECT_EXC = new BackendConnectionProblem(
l('Unable to connect to the [SOCKET] in backend [BACKENDID]: [MSG]',
Array('BACKENDID' => $this->backendId,
'SOCKET' => $this->socketPath,
'MSG' => $errstr)));
throw $this->CONNECT_EXC;
}
}
/*private function verifyLivestatusVersion() {
$result = $this->queryLivestatusSingleColumn("GET status\nColumns: livestatus_version\n");
$result[0] = '1.1.7rc1';
$version = str_replace('.', '0', $result[0]);
$version = str_replace('i', '0', $version);
$version = str_replace('b', '1', $version);
$version = (int) str_replace('rc', '2', $version);
if($version < 1010903) {
throw new BackendConnectionProblem(
l('The livestatus version [VERSION] used in backend [BACKENDID] is too old. Please update.',
Array('BACKENDID' => $this->backendId, 'VERSION' => $result[0])));
}
}*/
/**
* PRIVATE queryLivestatus()
*
* Queries the livestatus socket and returns the result as array
*
* @param String Query to send to the socket
* @return Array Results of the query
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function queryLivestatus($query, $response = true) {
// Only connect when no connection opened yet
if($this->SOCKET === null) {
$this->connectSocket();
// Check if the livestatus version is OK
//$this->verifyLivestatusVersion();
}
//$fh = fopen('/tmp/live', 'a');
//fwrite($fh, $query."\n\n");
//fclose($fh);
//Add authorization data to mk livestatus query
if(cfg('global', 'only_permitted_objects') == true) {
global $AUTH;
$userName = $AUTH->getUser();
$query .= "AuthUser: $userName\n";
}
// Query to get a json formated array back
// Use KeepAlive with fixed16 header
if($response) {
$query .= "OutputFormat: json\n";
if ((bool)cfg('backend_'.$this->backendId, 'keepalive'))
$query .= "KeepAlive: on\n";
$query .= "ResponseHeader: fixed16\n\n";
}
// Disable regular error reporting to suppress php error messages
$oldLevel = error_reporting(0);
$write = fwrite($this->SOCKET, $query);
error_reporting($oldLevel);
if($write=== false)
throw new BackendConnectionProblem(l('Problem while writing to socket [SOCKET] in backend [BACKENDID]: [MSG]',
Array('BACKENDID' => $this->backendId,
'SOCKET' => $this->socketPath,
'MSG' => 'Error while sending query to socket.')));
if($write !== strlen($query))
throw new BackendConnectionProblem(l('Problem while writing to socket [SOCKET] in backend [BACKENDID]: [MSG]',
Array('BACKENDID' => $this->backendId,
'SOCKET' => $this->socketPath,
'MSG' => 'Connection terminated.')));
// Return here if no answer is expected
if(!$response)
return;
// Read 16 bytes to get the status code and body size
$read = $this->readSocket(16);
// Catch problem while reading
if($read === false)
throw new BackendConnectionProblem(l('Problem while reading from socket [SOCKET] in backend [BACKENDID]: [MSG]',
Array('BACKENDID' => $this->backendId,
'SOCKET' => $this->socketPath,
'MSG' => 'Error while reading socket (header)')));
// Extract status code
$status = substr($read, 0, 3);
// Extract content length
$len = intval(trim(substr($read, 4, 11)));
// Read socket until end of data
$read = $this->readSocket($len);
// Catch problem while reading
if($read === false) {
throw new BackendConnectionProblem(l('Problem while reading from socket [SOCKET] in backend [BACKENDID]: [MSG]',
Array('BACKENDID' => $this->backendId,
'SOCKET' => $this->socketPath,
'MSG' => 'Error while reading socket (content)')));
}
// Catch errors (Like HTTP 200 is OK)
if($status != "200") {
throw new BackendConnectionProblem(l('Problem while reading from socket [SOCKET] in backend [BACKENDID]: [MSG]',
Array('BACKENDID' => $this->backendId,
'SOCKET' => $this->socketPath,
'MSG' => $read)));
}
//$fh = fopen('/tmp/live', 'a');
//fwrite($fh, $read."\n\n");
//fclose($fh);
// Decode the json response
$obj = json_decode(utf8_encode($read));
// TEST: Disable KeepAlive:
//fclose($this->SOCKET);
//$this->SOCKET = null;
// json_decode returns null on syntax problems
if($obj === null) {
throw new BackendInvalidResponse(l('The response has an invalid format in backend [BACKENDID].',
Array('BACKENDID' => $this->backendId)));
} else {
// Return the response object
return $obj;
}
}
/**
* PRIVATE readSocket()
*
* Method for reading a fixed amount of bytest from the socket
*
* @param Integer Number of bytes to read
* @return String The read bytes
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function readSocket($len) {
$offset = 0;
$socketData = '';
while($offset < $len) {
if(($data = @fread($this->SOCKET, $len - $offset)) === false) {
return false;
}
if(($dataLen = strlen($data)) === 0) {
break;
}
$offset += $dataLen;
$socketData .= $data;
}
return $socketData;
}
/**
* PRIVATE queryLivestatusSingleRow()
*
* Queries the livestatus socket for a single row
*
* @param String Query to send to the socket
* @return Array Results of the query
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function queryLivestatusSingleRow($query) {
$l = $this->queryLivestatus($query);
if(isset($l[0])) {
return $l[0];
} else {
return Array();
}
}
/**
* PRIVATE queryLivestatusSingleColumn()
*
* Queries the livestatus socket for a single column in several rows
*
* @param String Query to send to the socket
* @return Array Results of the query
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function queryLivestatusSingleColumn($query) {
$l = $this->queryLivestatus($query);
$result = Array();
foreach($l as $line) {
$result[] = $line[0];
}
return $result;
}
/**
* PRIVATE queryLivestatusList()
*
* Queries the livestatus socket for a list of objects
*
* @param String Query to send to the socket
* @return Array Results of the query
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function queryLivestatusList($query) {
$l = $this->queryLivestatus($query);
$result = Array();
foreach($l as $line) {
$result = array_merge($result, $line[0]);
}
return $result;
}
/**
* PUBLIC query()
* This is a special method which is currently unused within NagVis.
* It has been added as interface to the std_lq.php script.
*/
public function query($type, $query) {
switch($type) {
case 'column':
return $this->queryLivestatusSingleColumn($query);
break;
case 'row':
return $this->queryLivestatusSingleRow($query);
break;
default:
return $this->queryLivestatus($query);
break;
}
}
/**
* PUBLIC getObjects()
*
* Queries the livestatus socket for a list of objects
*
* @param String Type of object
* @param String Name1 of the objecs
* @param String Name2 of the objecs
* @return Array Results of the query
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
public function getObjects($type, $name1Pattern = '', $name2Pattern = '', $add_filter = '') {
$ret = Array();
$filter = '';
$sFile = '';
switch($type) {
case 'host':
case 'hostgroup':
case 'servicegroup':
$l = $this->queryLivestatus("GET ".$type."s\nColumns: name alias\n".$add_filter);
break;
case 'service':
$query = "GET services\nColumns: host_name description\n";
if($name1Pattern) {
$query .= "Filter: host_name = " . $name1Pattern . "\n";
}
$query .= $add_filter;
$l = $this->queryLivestatus($query);
break;
default:
return Array();
break;
}
reset($l);
$result = Array();
foreach($l as $entry) {
$result[] = Array('name1' => $entry[0], 'name2' => $entry[1]);
}
return $result;
}
/**
* PRIVATE parseFilter()
*
* Parses the filter array to backend
*
* @param Array List of objects to query
* @param Array List of filters to apply
* @return String Parsed filters
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
private function parseFilter($objects, $filters, $isMemberQuery = false,
$isCountQuery = false, $isHostQuery = true) {
$aFilters = Array();
foreach($objects AS $OBJS) {
$objFilters = Array();
foreach($filters AS $filter) {
if ($isHostQuery && $filter['key'] == 'host_name')
$key = 'name';
else
$key = $filter['key'];
// Array('key' => 'host_name', 'operator' => '=', 'name'),
switch($key) {
case 'name':
case 'host_name':
case 'host_groups':
case 'service_description':
case 'groups':
case 'service_groups':
case 'hostgroup_name':
case 'group_name':
case 'servicegroup_name':
if($key != 'service_description')
$val = $OBJS[0]->getName();
else
$val = $OBJS[0]->getServiceDescription();
$objFilters[] = 'Filter: '.$key.' '.$filter['op'].' '.$val."\n";
break;
default:
throw new BackendConnectionProblem('Invalid filter key ('.$key.')');
break;
}
}
// is this a dynamic group with already compiled filters?
if($isMemberQuery && $OBJS[0]->getType() == 'dyngroup') {
return $OBJS[0]->getObjectFilter();
}
// Are there child exclude filters defined for this object?
// The objType is the type of the objects to query the data for
if($isMemberQuery && $OBJS[0]->hasExcludeFilters($isCountQuery)) {
$filter = $OBJS[0]->getExcludeFilter($isCountQuery);
$objType = $OBJS[0]->getType();
if($objType == 'host') {
$parts = explode('~~', $filter);
if(!isset($parts[1]))
$objFilters[] = 'Filter: service_description !~~ '.$filter."\n";
} elseif($objType == 'hostgroup' && $isHostQuery) {
$parts = explode('~~', $filter);
if(!isset($parts[1]))
$objFilters[] = 'Filter: host_name !~~ '.$parts[0]."\n";
} elseif(($objType == 'hostgroup' && !$isHostQuery) || $objType == 'servicegroup') {
$parts = explode('~~', $filter);
if(isset($parts[1]))
$objFilters[] = 'Filter: host_name ~~ '.$parts[0]."\n"
.'Filter: service_description ~~ '.$parts[1]."\n"
."And: 2\n"
."Negate:\n";
else
$objFilters[] = 'Filter: host_name !~~ '.$parts[0]."\n";
}
}
// the object specific filters all need to match
$count = count($objFilters);
if($count > 1)
$count = 'And: '.$count."\n";
else
$count = '';
$aFilters[] = implode($objFilters).$count;
}
$count = count($aFilters);
if($count > 1)
$count = 'Or: '.$count."\n";
else
$count = '';
return implode($aFilters).$count;
}
private function serviceStateStats($stateAttr) {
$staleness_thresh = cfg('global', 'staleness_threshold');
return
// Count PENDING
"Stats: has_been_checked = 0\n" .
// Count OK
"Stats: ".$stateAttr." = 0\n" .
"Stats: has_been_checked != 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness < ".$staleness_thresh."\n" .
"StatsAnd: 5\n" .
// Count OK (STALE)
"Stats: ".$stateAttr." = 0\n" .
"Stats: has_been_checked != 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness >= ".$staleness_thresh."\n" .
"StatsAnd: 5\n" .
// Count OK (DOWNTIME)
"Stats: ".$stateAttr." = 0\n" .
"Stats: has_been_checked != 0\n" .
"Stats: scheduled_downtime_depth > 0\n" .
"Stats: host_scheduled_downtime_depth > 0\n" .
"StatsOr: 2\n" .
"StatsAnd: 3\n" .
// Count WARNING
"Stats: ".$stateAttr." = 1\n" .
"Stats: acknowledged = 0\n" .
"Stats: host_acknowledged = 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness < ".$staleness_thresh."\n" .
"StatsAnd: 6\n" .
// Count WARNING (STALE)
"Stats: ".$stateAttr." = 1\n" .
"Stats: acknowledged = 0\n" .
"Stats: host_acknowledged = 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness >= ".$staleness_thresh."\n" .
"StatsAnd: 6\n" .
// Count WARNING(ACK)
"Stats: ".$stateAttr." = 1\n" .
"Stats: acknowledged = 1\n" .
"Stats: host_acknowledged = 1\n" .
"StatsOr: 2\n" .
"StatsAnd: 2\n" .
// Count WARNING(DOWNTIME)
"Stats: ".$stateAttr." = 1\n" .
"Stats: scheduled_downtime_depth > 0\n" .
"Stats: host_scheduled_downtime_depth > 0\n" .
"StatsOr: 2\n" .
"StatsAnd: 2\n" .
// Count CRITICAL
"Stats: ".$stateAttr." = 2\n" .
"Stats: acknowledged = 0\n" .
"Stats: host_acknowledged = 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness < ".$staleness_thresh."\n" .
"StatsAnd: 6\n" .
// Count CRITICAL (STALE)
"Stats: ".$stateAttr." = 2\n" .
"Stats: acknowledged = 0\n" .
"Stats: host_acknowledged = 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness >= ".$staleness_thresh."\n" .
"StatsAnd: 6\n" .
// Count CRITICAL(ACK)
"Stats: ".$stateAttr." = 2\n" .
"Stats: acknowledged = 1\n" .
"Stats: host_acknowledged = 1\n" .
"StatsOr: 2\n" .
"StatsAnd: 2\n" .
// Count CRITICAL(DOWNTIME)
"Stats: ".$stateAttr." = 2\n" .
"Stats: scheduled_downtime_depth > 0\n" .
"Stats: host_scheduled_downtime_depth > 0\n" .
"StatsOr: 2\n" .
"StatsAnd: 2\n" .
// Count UNKNOWN
"Stats: ".$stateAttr." = 3\n" .
"Stats: acknowledged = 0\n" .
"Stats: host_acknowledged = 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness < ".$staleness_thresh."\n" .
"StatsAnd: 6\n" .
// Count UNKNOWN (STALE)
"Stats: ".$stateAttr." = 3\n" .
"Stats: acknowledged = 0\n" .
"Stats: host_acknowledged = 0\n" .
"Stats: scheduled_downtime_depth = 0\n" .
"Stats: host_scheduled_downtime_depth = 0\n" .
"Stats: staleness >= ".$staleness_thresh."\n" .
"StatsAnd: 6\n" .
// Count UNKNOWN(ACK)
"Stats: ".$stateAttr." = 3\n" .
"Stats: acknowledged = 1\n" .
"Stats: host_acknowledged = 1\n" .
"StatsOr: 2\n" .
"StatsAnd: 2\n" .
// Count UNKNOWN(DOWNTIME)
"Stats: ".$stateAttr." = 3\n" .
"Stats: scheduled_downtime_depth > 0\n" .
"Stats: host_scheduled_downtime_depth > 0\n" .
"StatsOr: 2\n" .
"StatsAnd: 2\n";
}
/**
* PUBLIC getHostState()
*
* Queries the livestatus socket for the state of one or several hosts
*
* @param Array List of objects to query
* @param Array List of filters to apply
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
public function getHostState($objects, $options, $filters, $isMemberQuery = false) {
$objFilter = $this->parseFilter($objects, $filters, $isMemberQuery, !COUNT_QUERY, HOST_QUERY);
if($options & 1)
$stateAttr = 'hard_state';
else
$stateAttr = 'state';
$q = "GET hosts\n".
"Columns: ".$stateAttr." plugin_output alias display_name ".
"address notes last_check next_check state_type ".
"current_attempt max_check_attempts last_state_change ".
"last_hard_state_change perf_data acknowledged ".
"scheduled_downtime_depth has_been_checked name ".
"check_command custom_variable_names custom_variable_values staleness\n".
$objFilter;
$l = $this->queryLivestatus($q);
$arrReturn = Array();
if(is_array($l) && count($l) > 0) {
foreach($l as $e) {
// Catch unchecked objects
// $e[16]: has_been_checked
// $e[0]: state
if($e[16] == 0 || $e[0] === '') {
$arrReturn[$e[17]] = Array(
UNCHECKED,
l('hostIsPending', Array('HOST' => $e[17])),
null,
null,
null,
);
continue;
}
switch($e[0]) {
case "0": $state = UP; break;
case "1": $state = DOWN; break;
case "2": $state = UNREACHABLE; break;
default: $state = UNKNOWN; break;
}
// 15: acknowledged
$acknowledged = $state != UP && $e[14] == 1;
// 19: keys, 20: values
if(isset($e[19][0]) && isset($e[20][0]))
$custom_vars = array_combine($e[19], $e[20]);
else
$custom_vars = null;
// If there is a downtime for this object, save the data
// $e[15]: scheduled_downtime_depth
$dt_details = array(null, null, null, null);
if(isset($e[15]) && $e[15] > 0) {
$in_downtime = true;
// This handles only the first downtime. But this is not backend
// specific. The other backends do this as well.
$data = $this->queryLivestatusSingleRow(
"GET downtimes\n".
"Columns: author comment start_time end_time\n" .
"Filter: host_name = ".$e[17]."\n");
if(isset($data[0]))
$dt_details = $data;
} else {
$in_downtime = false;
}
$arrReturn[$e[17]] = Array(
$state,
$e[1], // output
$acknowledged,
$in_downtime,
(float)$e[21], // staleness
$e[8], // state type
$e[9], // current attempt
$e[10], // max attempts
$e[6], // last check
$e[7], // next check
$e[12], // last hard state change
$e[11], // last state change
$e[13], // perfdata
$e[3], // display name
$e[2], // alias
$e[4], // address
$e[5], // notes
$e[18], // check command
$custom_vars,
$dt_details[0], // downtime author
$dt_details[1], // downtime comment
$dt_details[2], // downtime start
$dt_details[3], // downtime end
);
}
}
return $arrReturn;
}
/**
* PUBLIC getServiceState()
*
* Queries the livestatus socket for a specific service
* or all services of a host
*
* @param Array List of objects to query
* @param Array List of filters to apply
* @author Mathias Kettner <mk@mathias-kettner.de>
* @author Lars Michelsen <lm@larsmichelsen.com>
*/
public function getServiceState($objects, $options, $filters, $isMemberQuery = false) {
$objFilter = $this->parseFilter($objects, $filters, $isMemberQuery, !COUNT_QUERY, !HOST_QUERY);
if($options & 1)
$stateAttr = 'last_hard_state';
else
$stateAttr = 'state';
$l = $this->queryLivestatus(
"GET services\n" .
$objFilter.
"Columns: description display_name ".$stateAttr." ".
"host_alias host_address plugin_output notes last_check next_check ".
"state_type current_attempt max_check_attempts last_state_change ".
"last_hard_state_change perf_data scheduled_downtime_depth ".
"acknowledged host_acknowledged host_scheduled_downtime_depth ".
"has_been_checked host_name check_command custom_variable_names custom_variable_values ".
"staleness\n");
$arrReturn = Array();
if(is_array($l) && count($l) > 0) {
foreach($l as $e) {
// test for the correct key
if(isset($objects[$e[20].'~~'.$e[0]])) {
$specific = true;
$key = $e[20].'~~'.$e[0];
} else {
$specific = false;
$key = $e[20];
}
// Catch pending objects
// $e[19]: has_been_checked
// $e[2]: state
if($e[19] == 0 || $e[2] === '') {
$svc = array_fill(0, EXT_STATE_SIZE, null);
$svc[DESCRIPTION] = $e[0];
$svc[DISPLAY_NAME] = $e[1];
$svc[STATE] = PENDING;
$svc[OUTPUT] = l('serviceNotChecked', Array('SERVICE' => $e[0]));
} else {
switch ($e[2]) {
case "0": $state = OK; break;
case "1": $state = WARNING; break;
case "2": $state = CRITICAL; break;
case "3": $state = UNKNOWN; break;
default: $state = UNKNOWN; break;
}
/**
* Handle host/service acks
*
* If state is not OK (=> WARN, CRIT, UNKNOWN) and service is not
* acknowledged => check for acknowledged host
*/
// $e[16]: acknowledged
// $e[17]: host_acknowledged
$acknowledged = $state != OK && ($e[16] == 1 || $e[17] == 1);
// Handle host/service downtimes
// $e[15]: scheduled_downtime_depth
// $e[18]: host_scheduled_downtime_depth
$dt_details = array(null, null, null, null);
if((isset($e[15]) && $e[15] > 0) || (isset($e[18]) && $e[18] > 0)) {
$in_downtime = true;
// This handles only the first downtime. But this is not backend
// specific. The other backends do this as well.
// Handle host/service downtime difference
if(isset($e[15]) && $e[15] > 0) {
// Service downtime
$data = $this->queryLivestatusSingleRow(
"GET downtimes\n".
"Columns: author comment start_time end_time\n" .
"Filter: host_name = ".$e[20]."\n" .
"Filter: service_description = ".$e[0]."\n");
} else {
// Host downtime
$data = $this->queryLivestatusSingleRow(
"GET downtimes\n".
"Columns: author comment start_time end_time\n" .
"Filter: host_name = ".$e[20]."\n");
}
if(isset($data[0]))
$dt_details = $data;
} else {
$in_downtime = false;
}
if(isset($e[22][0]) && isset($e[23][0]))
$custom_vars = array_combine($e[22], $e[23]);
else
$custom_vars = null;
$svc = array(
$state,
$e[5], // output
$acknowledged,
$in_downtime,
(float)$e[24], // staleness
$e[9], // state type
$e[10], // current attempt
$e[11], // max check attempts
$e[7], // last check
$e[8], // next check
$e[13], // last hard state change
$e[12], // last state change
$e[14], // perfdata
$e[1], // display name
$e[3], // alias
$e[4], // address
$e[6], // notes
$e[21], // check command
$custom_vars,
$dt_details[0], // dt author
$dt_details[1], // dt data
$dt_details[2], // dt start
$dt_details[3], // dt end
$e[0], // descr
);
}
if($specific) {
$arrReturn[$key] = $svc;
} else {
if(!isset($arrReturn[$key]))
$arrReturn[$key] = array();
$arrReturn[$key][] = $svc;
}
}
}
return $arrReturn;
}
/**
* Queries the livestatus socket for host state counts. The information
* are used to calculate the summary output and the summary state of a
* host and a well performing alternative to the existing recurisve
* algorithm.
*/
public function getHostMemberCounts($objects, $options, $filters) {
$objFilter = $this->parseFilter($objects, $filters, MEMBER_QUERY, COUNT_QUERY, !HOST_QUERY);
if($options & 1)
$stateAttr = 'last_hard_state';
else
$stateAttr = 'state';
// Get service information
$l = $this->queryLivestatus("GET services\n" .
$objFilter.
$this->serviceStateStats($stateAttr).
"Columns: host_name host_alias\n");
$arrReturn = Array();
if(is_array($l) && count($l) > 0) {
// livestatus previous 1.1.9i3 answers without host_alias - these users should update.
if(!isset($l[0][13]))
throw new BackendInvalidResponse(
l('Livestatus version used in backend [BACKENDID] is too old. Please update.',
Array('BACKENDID' => $this->backendId)));
foreach ($l as $e) {
// Workaround for Icinga 2 which answers stats queries for not existing objects with
// 0 stats but with missing host_name and host_alias columns. So the number of answer
// columns is different leading to an exception in the code below.
if (count($e) != 18)
continue;
$arrReturn[$e[0]] = Array(
//'details' => Array('alias' => $e[1]),
'counts' => Array(
PENDING => Array(