Livestatus.pm

filter: Statementstmt 23.2% 136 / 586 Branchbran 16.2% 58 / 356 Conditioncond 9.0% 10 / 111 MC/DCmcdc 1.4% 1 / 67 Subroutinesub 42.5% 17 / 40 Podpod 100% 17 / 17 totaltotal 20.3% 239 / 1177 CC 234 SCAR 67.0
CC
234
Cov
19%
_send
2970.0
_read_socket_do
930.0
selectall_arrayref
600.0
CRAP 810.7
↑ Summary Livestatus/INET.pm »
1 package Monitoring::Livestatus;
2  
3 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use Carp qw/carp confess/;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use Cpanel::JSON::XS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 4 ▶use Data::Dumper qw/Dumper/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 4 ▶use IO::Select ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Storable qw/dclone/;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 4 ▶use Monitoring::Livestatus::INET ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 4 ▶use Monitoring::Livestatus::UNIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 4 our $VERSION = '0.86';
15  
16  
17 # list of allowed options
18 4 my $allowed_options = {
19 'addpeer' => 1,
20 'backend' => 1,
21 'columns' => 1,
22 'deepcopy' => 1,
23 'header' => 1,
24 'limit' => 1,
25 'limit_start' => 1,
26 'limit_length' => 1,
27 'rename' => 1,
28 'slice' => 1,
29 'sum' => 1,
30 'callbacks' => 1,
31 'wrapped_json' => 1,
32 'sort' => 1,
33 'offset' => 1,
34 };
35  
36 =head1 NAME
37  
38 Monitoring::Livestatus - Perl API for check_mk livestatus to access runtime
39 data from Nagios and Icinga
40  
41 =head1 SYNOPSIS
42  
43 use Monitoring::Livestatus;
44 my $ml = Monitoring::Livestatus->new(
45 socket => '/var/lib/livestatus/livestatus.sock'
46 );
47 my $hosts = $ml->selectall_arrayref("GET hosts");
48  
49 =head1 DESCRIPTION
50  
51 This module connects via socket/tcp to the livestatus addon for Naemon, Nagios,
52 Icinga and Shinken. You first have to install and activate the livestatus addon
53 in your monitoring installation.
54  
55 =head1 CONSTRUCTOR
56  
57 =head2 new ( [ARGS] )
58  
59 Creates an C<Monitoring::Livestatus> object. C<new> takes at least the
60 socketpath. Arguments are in key-value pairs.
61  
62 =over 4
63  
64 =item socket
65  
66 path to the UNIX socket of check_mk livestatus
67  
68 =item server
69  
70 server address when using a TCP connection
71  
72 =item peer
73  
74 alternative way to set socket or server, if value contains ':' server is used,
75 else socket
76  
77 =item name
78  
79 human readable name for this connection, defaults to the the socket/server
80 address
81  
82 =item verbose
83  
84 verbose mode
85  
86 =item line_separator
87  
88 ascii code of the line separator, defaults to 10, (newline)
89  
90 =item column_separator
91  
92 ascii code of the column separator, defaults to 0 (null byte)
93  
94 =item list_separator
95  
96 ascii code of the list separator, defaults to 44 (comma)
97  
98 =item host_service_separator
99  
100 ascii code of the host/service separator, defaults to 124 (pipe)
101  
102 =item keepalive
103  
104 enable keepalive. Default is off
105  
106 =item errors_are_fatal
107  
108 errors will die with an error message. Default: on
109  
110 =item warnings
111  
112 show warnings
113 currently only querys without Columns: Header will result in a warning
114  
115 =item timeout
116  
117 set a general timeout. Used for connect and querys, no default
118  
119 =item query_timeout
120  
121 set a query timeout. Used for retrieving querys, Default 60sec
122  
123 =item connect_timeout
124  
125 set a connect timeout. Used for initial connections, default 5sec
126  
127 =back
128  
129 If the constructor is only passed a single argument, it is assumed to
130 be a the C<peer> specification. Use either socker OR server.
131  
132 =cut
133  
134 24 ▶sub new {
Subroutine new: called CC=16 SCAR=29.8
Pod documented
135 24 my($class,@args) = @_;
136 24 ▶ unshift(@args, 'peer') if scalar @args == 1;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @args == 1 3 21 24
137 24 my(%options) = @args;
138  
139 24 my $self = {
140 'verbose' => 0, # enable verbose output
141 'socket' => undef, # use unix sockets
142 'server' => undef, # use tcp connections
143 'peer' => undef, # use for socket / server connections
144 'name' => undef, # human readable name
145 'line_separator' => 10, # defaults to newline
146 'column_separator' => 0, # defaults to null byte
147 'list_separator' => 44, # defaults to comma
148 'host_service_separator' => 124, # defaults to pipe
149 'keepalive' => 0, # enable keepalive?
150 'errors_are_fatal' => 1, # die on errors
151 'backend' => undef, # should be keept undef, used internally
152 'timeout' => undef, # timeout for tcp connections
153 'query_timeout' => undef, # query timeout for tcp connections
154 'connect_timeout' => 30, # connect timeout for tcp connections
155 'warnings' => 1, # show warnings, for example on querys without Column: Header
156 'logger' => undef, # logger object used for statistical informations and errors / warnings
157 'deepcopy' => undef, # copy result set to avoid errors with tied structures
158 'retries_on_connection_error' => 3, # retry x times to connect
159 'retry_interval' => 1, # retry after x seconds
160 # tls options
161 'cert' => undef,
162 'key' => undef,
163 'ca_file' => undef,
164 'verify' => undef,
165 'verifycn_name' => undef,
166 };
167  
168 24 my %old_key = (
169 line_seperator => 'line_separator',
170 column_seperator => 'column_separator',
171 list_seperator => 'list_separator',
172 host_service_seperator => 'host_service_separator',
173 );
174  
175 # previous versions had spelling errors in the key name
176 24 for my $opt_key (keys %old_key) {
177 96 ▶ if(exists $options{$opt_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{$opt_key}) 0 96 96
178 0 my $value = $options{$opt_key};
179 0 $options{ $old_key{$opt_key} } = $value;
180 0 delete $options{$opt_key};
181 }
182 }
183  
184 24 for my $opt_key (keys %options) {
185 93 ▶ if(exists $self->{$opt_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $self->{$opt_key}) { } 93 0 93
186 93 $self->{$opt_key} = $options{$opt_key};
187 }
188 else {
189 0 confess("unknown option: $opt_key");
190 }
191 }
192  
193 24 ▶ if($self->{'verbose'} && !defined $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"verbose"} and not defined $self->{"logger"}) 0 24 24
Condition33%1/3
$self->{"verbose"} and not defined $self->{"logger"}
!ll&&!rl&&r
2400
MC/DC0%0/2
$self->{"verbose"} and not defined $self->{"logger"}
$self->{"verbose"} not defined $self->{"logger"}
Truth table33%1/3
A and not(B)
A= $self->{"verbose"}B= not defined $self->{"logger"}
ABresult
0X0
100
111
194 0 confess('please specify a logger object when using verbose mode');
195 }
196  
197 # setting a general timeout?
198 24 ▶ if(defined $self->{'timeout'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"timeout"}) 2 22 24
199 2 $self->{'query_timeout'} = $self->{'timeout'};
200 2 $self->{'connect_timeout'} = $self->{'timeout'};
201 }
202  
203 24 bless $self, $class;
204  
205 # set our peer(s) from the options
206 24 my $peer = $self->_get_peer();
207  
208 24 ▶ if(!defined $self->{'backend'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"backend"}) 10 14 24
209 10 $options{'name'} = $peer->{'name'};
210 10 $options{'peer'} = $peer->{'peer'};
211 10 ▶ if($peer->{'type'} eq 'UNIX') {
Branch: 2 branches
BranchTrueFalseTotal
if ($peer->{'type'} eq 'UNIX') { } 8 2 10
elsif ($peer->{'type'} eq 'INET') { } 2 0 2
212 8 $self->{'CONNECTOR'} = Monitoring::Livestatus::UNIX->new(%options);
213 }
214 elsif($peer->{'type'} eq 'INET') {
215 2 $self->{'CONNECTOR'} = Monitoring::Livestatus::INET->new(%options);
216 }
217 10 $self->{'peer'} = $peer->{'peer'};
218 }
219  
220 # set names and peer for non multi backends
221 24 ▶ if(defined $self->{'CONNECTOR'}->{'name'} && !defined $self->{'name'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"CONNECTOR"}{"name"} and not defined $self->{"name"}) 10 14 24
Condition66%2/3
defined $self->{"CONNECTOR"}{"name"} and not defined $self->{"name"}
!ll&&!rl&&r
14010
MC/DC50%1/2
defined $self->{"CONNECTOR"}{"name"} and not defined $self->{"name"}
defined $self->{"CONNECTOR"}{"name"} not defined $self->{"name"}
Truth table66%2/3
A and not(B)
A= defined $self->{"CONNECTOR"}{"name"}B= not defined $self->{"name"}
ABresult
0X0
100
111
222 10 $self->{'name'} = $self->{'CONNECTOR'}->{'name'};
223 }
224 24 ▶ if(defined $self->{'CONNECTOR'}->{'peer'} && !defined $self->{'peer'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"CONNECTOR"}{"peer"} and not defined $self->{"peer"}) 0 24 24
Condition66%2/3
defined $self->{"CONNECTOR"}{"peer"} and not defined $self->{"peer"}
!ll&&!rl&&r
14100
MC/DC0%0/2
defined $self->{"CONNECTOR"}{"peer"} and not defined $self->{"peer"}
defined $self->{"CONNECTOR"}{"peer"} not defined $self->{"peer"}
Truth table66%2/3
A and not(B)
A= defined $self->{"CONNECTOR"}{"peer"}B= not defined $self->{"peer"}
ABresult
0X0
100
111
225 0 $self->{'peer'} = $self->{'CONNECTOR'}->{'peer'};
226 }
227  
228 24 return $self;
229 }
230  
231  
232 ########################################
233  
234 =head1 METHODS
235  
236 =head2 do
237  
238 do($statement)
239 do($statement, %opts)
240  
241 Send a single statement without fetching the result.
242 Always returns true.
243  
244 =cut
245  
246 0 ▶sub do {
Subroutine do: not called CC=1 SCAR=6.9
Pod documented
247 0 my($self, $statement, $opt) = @_;
248 0 $self->_send($statement, $opt);
249 0 return(1);
250 }
251  
252  
253 ########################################
254  
255 =head2 selectall_arrayref
256  
257 selectall_arrayref($statement)
258 selectall_arrayref($statement, %opts)
259 selectall_arrayref($statement, %opts, $limit )
260  
261 Sends a query and returns an array reference of arrays
262  
263 my $arr_refs = $ml->selectall_arrayref("GET hosts");
264  
265 to get an array of hash references do something like
266  
267 my $hash_refs = $ml->selectall_arrayref(
268 "GET hosts", { Slice => {} }
269 );
270  
271 to get an array of hash references from the first 2 returned rows only
272  
273 my $hash_refs = $ml->selectall_arrayref(
274 "GET hosts", { Slice => {} }, 2
275 );
276  
277 you may use limit to limit the result to this number of rows
278  
279 column aliases can be defined with a rename hash
280  
281 my $hash_refs = $ml->selectall_arrayref(
282 "GET hosts", {
283 Slice => {},
284 rename => {
285 'name' => 'host_name'
286 }
287 }
288 );
289  
290 =cut
291  
292 0 ▶sub selectall_arrayref {
Subroutine selectall_arrayref: not called CC=24 SCAR=64.0
Pod documented
293 0 my($self, $statement, $opt, $limit, $result) = @_;
294 0 ▶ $limit = 0 unless defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $limit 0 0 0
295  
296 # make opt hash keys lowercase
297 0 ▶ $opt = &_lowercase_and_verify_options($self, $opt) unless $result;
Branch: 1 branch
BranchTrueFalseTotal
unless $result 0 0 0
298  
299 0 ▶ $self->_log_statement($statement, $opt, $limit) if !$result && $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if not $result and $self->{"verbose"} 0 0 0
Condition0%0/3
not $result and $self->{"verbose"}
!ll&&!rl&&r
000
MC/DC0%0/2
not $result and $self->{"verbose"}
not $result $self->{"verbose"}
Truth table0%0/3
not(A) and B
A= not $resultB= $self->{"verbose"}
ABresult
0X0
100
111
300  
301 0 ▶ if(!defined $result) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result) 0 0 0
302 0 $result = &_send($self, $statement, $opt);
303  
304 0 ▶ if(!defined $result) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result) 0 0 0
305 0 ▶ return unless $self->{'errors_are_fatal'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"errors_are_fatal"} 0 0 0
306 0 confess("got undef result for: $statement");
307 }
308 }
309  
310 # trim result set down to excepted row count
311 0 ▶ if(!$opt->{'offset'} && defined $limit && $limit >= 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $opt->{"offset"} and defined $limit and $limit >= 1) 0 0 0
Condition0%0/6
not $opt->{"offset"} and defined $limit and $limit >= 1
!ll&&!rl&&r
000
not $opt->{"offset"} and defined $limit
!ll&&!rl&&r
000
MC/DC0%0/3
not $opt->{"offset"} and defined $limit and $limit >= 1
not $opt->{"offset"} defined $limit $limit >= 1
Truth table0%0/4
not(A) and B and C
A= not $opt->{"offset"}B= defined $limitC= $limit >= 1
ABCresult
0XX0
10X0
1100
1111
312 0 ▶ if(scalar @{$result->{'result'}} > $limit) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$result->{"result"};} > $limit) 0 0 0
313 0 @{$result->{'result'}} = @{$result->{'result'}}[0..$limit-1];
314 }
315 }
316  
317 0 ▶ if($opt->{'slice'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"slice"}) 0 0 0
318 0 my $callbacks = $opt->{'callbacks'};
319 # make an array of hashes, inplace to safe memory
320 0 my $keys = $result->{'keys'};
321 # renamed columns
322 0 ▶ if($opt->{'rename'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"rename"}) 0 0 0
323 0 $keys = dclone($result->{'keys'});
324 0 my $keysize = scalar @{$keys};
325 0 ▶ for(my $x=0; $x<$keysize;$x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $keysize) 0 0 0
326 0 my $old = $keys->[$x];
327 0 ▶ if($opt->{'rename'}->{$old}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"rename"}{$old}) 0 0 0
328 0 $keys->[$x] = $opt->{'rename'}->{$old};
329 }
330 }
331 }
332 0 $result = $result->{'result'};
333 0 my $rnum = scalar @{$result};
334 0 ▶ for(my $x=0;$x<$rnum;$x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $rnum) 0 0 0
335 # sort array into hash slices
336 0 my %hash;
337 0 @hash{@{$keys}} = @{$result->[$x]};
338 # add callbacks
339 0 ▶ if($callbacks) {
Branch: 1 branch
BranchTrueFalseTotal
if ($callbacks) 0 0 0
340 0 for my $key (keys %{$callbacks}) {
341 0 $hash{$key} = $callbacks->{$key}->(\%hash);
342 }
343 }
344 0 $result->[$x] = \%hash;
345 }
346 0 return($result);
347 }
348  
349 0 ▶ if(exists $opt->{'callbacks'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opt->{"callbacks"}) 0 0 0
350 0 for my $res (@{$result->{'result'}}) {
351 # add callbacks
352 0 ▶ if(exists $opt->{'callbacks'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opt->{"callbacks"}) 0 0 0
353 0 for my $key (keys %{$opt->{'callbacks'}}) {
354 0 push @{$res}, $opt->{'callbacks'}->{$key}->($res);
355 }
356 }
357 }
358  
359 0 for my $key (keys %{$opt->{'callbacks'}}) {
360 0 push @{$result->{'keys'}}, $key;
361 }
362 }
363 0 return($result->{'result'});
364 }
365  
366  
367 ########################################
368  
369 =head2 selectall_hashref
370  
371 selectall_hashref($statement, $key_field)
372 selectall_hashref($statement, $key_field, %opts)
373  
374 Sends a query and returns a hashref with the given key
375  
376 my $hashrefs = $ml->selectall_hashref("GET hosts", "name");
377  
378 =cut
379  
380 0 ▶sub selectall_hashref {
Subroutine selectall_hashref: not called CC=5 SCAR=34.0
Pod documented
381 0 my($self, $statement, $key_field, $opt) = @_;
382  
383 0 $opt = &_lowercase_and_verify_options($self, $opt);
384  
385 0 $opt->{'slice'} = 1;
386  
387 0 ▶ confess('key is required for selectall_hashref') if !defined $key_field;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key_field 0 0 0
388  
389 0 my $result = $self->selectall_arrayref($statement, $opt);
390  
391 0 my %indexed;
392 0 for my $row (@{$result}) {
393 0 ▶ if($key_field eq '$peername') {
Branch: 2 branches
BranchTrueFalseTotal
if ($key_field eq '$peername') { } 0 0 0
elsif (not defined $row->{$key_field}) { } 0 0 0
394 0 $indexed{$self->peer_name} = $row;
395 }
396 elsif(!defined $row->{$key_field}) {
397 0 my %possible_keys = keys %{$row};
398 0 confess("key $key_field not found in result set, possible keys are: ".join(', ', sort keys %possible_keys));
399 } else {
400 0 $indexed{$row->{$key_field}} = $row;
401 }
402 }
403 0 return(\%indexed);
404 }
405  
406  
407 ########################################
408  
409 =head2 selectcol_arrayref
410  
411 selectcol_arrayref($statement)
412 selectcol_arrayref($statement, %opt )
413  
414 Sends a query an returns an arrayref for the first columns
415  
416 my $array_ref = $ml->selectcol_arrayref("GET hosts\nColumns: name");
417  
418 $VAR1 = [
419 'localhost',
420 'gateway',
421 ];
422  
423 returns an empty array if nothing was found
424  
425 to get a different column use this
426  
427 my $array_ref = $ml->selectcol_arrayref(
428 "GET hosts\nColumns: name contacts",
429 { Columns => [2] }
430 );
431  
432 you can link 2 columns in a hash result set
433  
434 my %hash = @{
435 $ml->selectcol_arrayref(
436 "GET hosts\nColumns: name contacts",
437 { Columns => [1,2] }
438 )
439 };
440  
441 produces a hash with host the contact assosiation
442  
443 $VAR1 = {
444 'localhost' => 'user1',
445 'gateway' => 'user2'
446 };
447  
448 =cut
449  
450 0 ▶sub selectcol_arrayref {
Subroutine selectcol_arrayref: not called CC=5 SCAR=34.0
Pod documented
451 0 my($self, $statement, $opt) = @_;
452  
453 # make opt hash keys lowercase
454 0 $opt = &_lowercase_and_verify_options($self, $opt);
455  
456 # if now colums are set, use just the first one
457 0 ▶ if(!defined $opt->{'columns'} || ref $opt->{'columns'} ne 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $opt->{"columns"} or ref $opt->{"columns"} ne "ARRAY") 0 0 0
Condition0%0/3
not defined $opt->{"columns"} or ref $opt->{"columns"} ne "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/2
not defined $opt->{"columns"} or ref $opt->{"columns"} ne "ARRAY"
not defined $opt->{"columns"} ref $opt->{"columns"} ne "ARRAY"
Truth table0%0/3
not(A) or B
A= not defined $opt->{"columns"}B= ref $opt->{"columns"} ne "ARRAY"
ABresult
1X1
011
000
458 0 @{$opt->{'columns'}} = qw{1};
459 }
460  
461 0 my $result = $self->selectall_arrayref($statement);
462  
463 0 my @column;
464 0 for my $row (@{$result}) {
465 0 for my $nr (@{$opt->{'columns'}}) {
466 0 push @column, $row->[$nr-1];
467 }
468 }
469 0 return(\@column);
470 }
471  
472  
473 ########################################
474  
475 =head2 selectrow_array
476  
477 selectrow_array($statement)
478 selectrow_array($statement, %opts)
479  
480 Sends a query and returns an array for the first row
481  
482 my @array = $ml->selectrow_array("GET hosts");
483  
484 returns undef if nothing was found
485  
486 =cut
487 0 ▶sub selectrow_array {
Subroutine selectrow_array: not called CC=2 SCAR=17.9
Pod documented
488 0 my($self, $statement, $opt) = @_;
489  
490 # make opt hash keys lowercase
491 0 $opt = &_lowercase_and_verify_options($self, $opt);
492  
493 0 my @result = @{$self->selectall_arrayref($statement, $opt, 1)};
494 0 ▶ return @{$result[0]} if scalar @result > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @result > 0 0 0 0
495 0 return;
496 }
497  
498  
499 ########################################
500  
501 =head2 selectrow_arrayref
502  
503 selectrow_arrayref($statement)
504 selectrow_arrayref($statement, %opts)
505  
506 Sends a query and returns an array reference for the first row
507  
508 my $arrayref = $ml->selectrow_arrayref("GET hosts");
509  
510 returns undef if nothing was found
511  
512 =cut
513 0 ▶sub selectrow_arrayref {
Subroutine selectrow_arrayref: not called CC=3 SCAR=24.8
Pod documented
514 0 my($self, $statement, $opt) = @_;
515  
516 # make opt hash keys lowercase
517 0 $opt = &_lowercase_and_verify_options($self, $opt);
518  
519 0 my $result = $self->selectall_arrayref($statement, $opt, 1);
520 0 ▶ return if !defined $result;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result 0 0 0
521 0 ▶ return $result->[0] if scalar @{$result} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$result;} > 0 0 0 0
522 0 return;
523 }
524  
525  
526 ########################################
527  
528 =head2 selectrow_hashref
529  
530 selectrow_hashref($statement)
531 selectrow_hashref($statement, %opt)
532  
533 Sends a query and returns a hash reference for the first row
534  
535 my $hashref = $ml->selectrow_hashref("GET hosts");
536  
537 returns undef if nothing was found
538  
539 =cut
540 0 ▶sub selectrow_hashref {
Subroutine selectrow_hashref: not called CC=3 SCAR=24.8
Pod documented
541 0 my($self, $statement, $opt) = @_;
542  
543 # make opt hash keys lowercase
544 0 $opt = &_lowercase_and_verify_options($self, $opt);
545 0 $opt->{slice} = 1;
546  
547 0 my $result = $self->selectall_arrayref($statement, $opt, 1);
548 0 ▶ return if !defined $result;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $result 0 0 0
549 0 ▶ return $result->[0] if scalar @{$result} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$result;} > 0 0 0 0
550 0 return;
551 }
552  
553  
554 ########################################
555  
556 =head2 selectscalar_value
557  
558 selectscalar_value($statement)
559 selectscalar_value($statement, %opt)
560  
561 Sends a query and returns a single scalar
562  
563 my $count = $ml->selectscalar_value("GET hosts\nStats: state = 0");
564  
565 returns undef if nothing was found
566  
567 =cut
568 0 ▶sub selectscalar_value {
Subroutine selectscalar_value: not called CC=3 SCAR=24.8
Pod documented
569 0 my($self, $statement, $opt) = @_;
570  
571 # make opt hash keys lowercase
572 0 $opt = &_lowercase_and_verify_options($self, $opt);
573  
574 0 my $row = $self->selectrow_arrayref($statement);
575 0 ▶ return if !defined $row;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $row 0 0 0
576 0 ▶ return $row->[0] if scalar @{$row} > 0;
Branch: 1 branch
BranchTrueFalseTotal
if scalar @{$row;} > 0 0 0 0
577 0 return;
578 }
579  
580 ########################################
581  
582 =head2 errors_are_fatal
583  
584 errors_are_fatal()
585 errors_are_fatal($value)
586  
587 Enable or disable fatal errors. When enabled the module will confess on any error.
588  
589 returns the current setting if called without new value
590  
591 =cut
592 0 ▶sub errors_are_fatal {
Subroutine errors_are_fatal: not called CC=2 SCAR=17.9
Pod documented
593 0 my($self, $value) = @_;
594 0 my $old = $self->{'errors_are_fatal'};
595  
596 0 $self->{'errors_are_fatal'} = $value;
597 0 ▶ $self->{'CONNECTOR'}->{'errors_are_fatal'} = $value if defined $self->{'CONNECTOR'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"CONNECTOR"} 0 0 0
598  
599 0 return $old;
600 }
601  
602 ########################################
603  
604 =head2 warnings
605  
606 warnings()
607 warnings($value)
608  
609 Enable or disable warnings. When enabled the module will carp on warnings.
610  
611 returns the current setting if called without new value
612  
613 =cut
614 0 ▶sub warnings {
Subroutine warnings: not called CC=2 SCAR=17.9
Pod documented
615 0 my($self, $value) = @_;
616 0 my $old = $self->{'warnings'};
617  
618 0 $self->{'warnings'} = $value;
619 0 ▶ $self->{'CONNECTOR'}->{'warnings'} = $value if defined $self->{'CONNECTOR'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"CONNECTOR"} 0 0 0
620  
621 0 return $old;
622 }
623  
624  
625  
626 ########################################
627  
628 =head2 verbose
629  
630 verbose()
631 verbose($values)
632  
633 Enable or disable verbose output. When enabled the module will dump out debug output
634  
635 returns the current setting if called without new value
636  
637 =cut
638 0 ▶sub verbose {
Subroutine verbose: not called CC=2 SCAR=17.9
Pod documented
639 0 my($self, $value) = @_;
640 0 my $old = $self->{'verbose'};
641  
642 0 $self->{'verbose'} = $value;
643 0 ▶ $self->{'CONNECTOR'}->{'verbose'} = $value if defined $self->{'CONNECTOR'};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"CONNECTOR"} 0 0 0
644  
645 0 return $old;
646 }
647  
648  
649 ########################################
650  
651 =head2 peer_addr
652  
653 $ml->peer_addr()
654  
655 returns the current peer address
656  
657 when using multiple backends, a list of all addresses is returned in list context
658  
659 =cut
660 9 ▶sub peer_addr {
Subroutine peer_addr: called CC=1 SCAR=0.0
Pod documented
661 9 my($self) = @_;
662 9 return ''.$self->{'peer'};
663 }
664  
665  
666 ########################################
667  
668 =head2 peer_name
669  
670 $ml->peer_name()
671 $ml->peer_name($string)
672  
673 if new value is set, name is set to this value
674  
675 always returns the current peer name
676  
677 when using multiple backends, a list of all names is returned in list context
678  
679 =cut
680 9 ▶sub peer_name {
Subroutine peer_name: called CC=3 SCAR=13.3
Pod documented
681 9 my($self, $value) = @_;
682  
683 9 ▶ if(defined $value and $value ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value and $value ne "") 0 9 9
Condition33%1/3
defined $value and $value ne ""
!ll&&!rl&&r
900
MC/DC0%0/2
defined $value and $value ne ""
defined $value $value ne ""
Truth table33%1/3
A and B
A= defined $valueB= $value ne ""
ABresult
0X0
100
111
684 0 $self->{'name'} = $value;
685 }
686  
687 9 return ''.$self->{'name'};
688 }
689  
690  
691 ########################################
692  
693 =head2 peer_key
694  
695 $ml->peer_key()
696  
697 returns a uniq key for this peer
698  
699 =cut
700 0 ▶sub peer_key {
Subroutine peer_key: not called CC=1 SCAR=6.9
Pod documented
701 0 my($self) = @_;
702 0 return $self->{'key'};
703 }
704  
705 ########################################
706 # INTERNAL SUBS
707 ########################################
708 0 ▶sub _send {
Subroutine _send: not called CC=54 SCAR=80.0
709 0 my($self, $statement, $opt) = @_;
710  
711 0 ▶ confess('duplicate data') if $opt->{'data'};
Branch: 1 branch
BranchTrueFalseTotal
if $opt->{"data"} 0 0 0
712  
713 0 delete $self->{'meta_data'};
714  
715 0 my $header = '';
716 0 my $keys;
717  
718 0 $Monitoring::Livestatus::ErrorCode = 0;
719 0 undef $Monitoring::Livestatus::ErrorMessage;
720  
721 0 ▶ return(490, $self->_get_error(490), undef) if !defined $statement;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $statement 0 0 0
722 0 chomp($statement);
723  
724 0 my($status,$msg,$body);
725 0 ▶ if($statement =~ m/^Separators:/mx) {
Branch: 9 branches
BranchTrueFalseTotal
if ($statement =~ /^Separators:/mx) { } 0 0 0
elsif ($statement =~ /^KeepAlive:/mx) { } 0 0 0
elsif ($statement =~ /^ResponseHeader:/mx) { } 0 0 0
elsif ($statement =~ /^ColumnHeaders:/mx) { } 0 0 0
elsif ($statement =~ /^OuputFormat:/mx) { } 0 0 0
elsif ($statement =~ /^Limit:\ (.*)$/mx and not $1 =~ /^\d+$/mx) { } 0 0 0
elsif ($statement =~ /^GET\ (.*)$/mx and $1 =~ /^\s*$/mx) { } 0 0 0
elsif ($statement =~ /^Columns:\ (.*)$/mx and $1 =~ /,/mx || $1 =~ /^\s*$/mx) { } 0 0 0
elsif (not $statement =~ /^GET\ /mx || $statement =~ /^COMMAND\ /mx) { } 0 0 0
726 0 $status = 492;
727 0 $msg = $self->_get_error($status);
728 }
729  
730 elsif($statement =~ m/^KeepAlive:/mx) {
731 0 $status = 496;
732 0 $msg = $self->_get_error($status);
733 }
734  
735 elsif($statement =~ m/^ResponseHeader:/mx) {
736 0 $status = 495;
737 0 $msg = $self->_get_error($status);
738 }
739  
740 elsif($statement =~ m/^ColumnHeaders:/mx) {
741 0 $status = 494;
742 0 $msg = $self->_get_error($status);
743 }
744  
745 elsif($statement =~ m/^OuputFormat:/mx) {
746 0 $status = 493;
747 0 $msg = $self->_get_error($status);
748 }
749  
750 # should be cought in mlivestatus directly
751 ▶ elsif($statement =~ m/^Limit:\ (.*)$/mx and $1 !~ m/^\d+$/mx) {
Condition0%0/3
$statement =~ /^Limit:\ (.*)$/mx and not $1 =~ /^\d+$/mx
!ll&&!rl&&r
000
MC/DC0%0/2
$statement =~ /^Limit:\ (.*)$/mx and not $1 =~ /^\d+$/mx
$statement =~ /^Limit:\ (.*)$/mx not $1 =~ /^\d+$/mx
Truth table0%0/3
A and not(B)
A= $statement =~ /^Limit:\ (.*)$/mxB= not $1 =~ /^\d+$/mx
ABresult
0X0
100
111
752 0 $status = 403;
753 0 $msg = $self->_get_error($status);
754 }
755 ▶ elsif($statement =~ m/^GET\ (.*)$/mx and $1 =~ m/^\s*$/mx) {
Condition0%0/3
$statement =~ /^GET\ (.*)$/mx and $1 =~ /^\s*$/mx
!ll&&!rl&&r
000
MC/DC0%0/2
$statement =~ /^GET\ (.*)$/mx and $1 =~ /^\s*$/mx
$statement =~ /^GET\ (.*)$/mx $1 =~ /^\s*$/mx
Truth table0%0/3
A and B
A= $statement =~ /^GET\ (.*)$/mxB= $1 =~ /^\s*$/mx
ABresult
0X0
100
111
756 0 $status = 403;
757 0 $msg = $self->_get_error($status);
758 }
759  
760 ▶ elsif($statement =~ m/^Columns:\ (.*)$/mx and ($1 =~ m/,/mx or $1 =~ /^\s*$/mx)) {
Condition0%0/6
$statement =~ /^Columns:\ (.*)$/mx and $1 =~ /,/mx || $1 =~ /^\s*$/mx
!ll&&!rl&&r
000
$1 =~ /,/mx or $1 =~ /^\s*$/mx
l!l&&r!l&&!r
000
MC/DC0%0/3
$statement =~ /^Columns:\ (.*)$/mx and $1 =~ /,/mx || $1 =~ /^\s*$/mx
$statement =~ /^Columns:\ (.*)$/mx $1 =~ /,/mx $1 =~ /^\s*$/mx
Truth table0%0/4
A and B or C
A= $statement =~ /^Columns:\ (.*)$/mxB= $1 =~ /,/mxC= $1 =~ /^\s*$/mx
ABCresult
0XX0
1000
11X1
1011
761 0 $status = 405;
762 0 $msg = $self->_get_error($status);
763 }
764 ▶ elsif($statement !~ m/^GET\ /mx and $statement !~ m/^COMMAND\ /mx) {
Condition0%0/3
$statement =~ /^GET\ /mx || $statement =~ /^COMMAND\ /mx
l!l&&r!l&&!r
000
MC/DC0%0/2
$statement =~ /^GET\ /mx || $statement =~ /^COMMAND\ /mx
$statement =~ /^GET\ /mx $statement =~ /^COMMAND\ /mx
Truth table0%0/3
A || B
A= $statement =~ /^GET\ /mxB= $statement =~ /^COMMAND\ /mx
ABresult
1X1
011
000
765 0 $status = 401;
766 0 $msg = $self->_get_error($status);
767 }
768  
769 else {
770  
771 # Add Limits header
772 0 ▶ if(defined $opt->{'limit_start'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"limit_start"}) 0 0 0
773 0 $statement .= "\nLimit: ".($opt->{'limit_start'} + $opt->{'limit_length'});
774 }
775  
776 # for querys with column header, no seperate columns will be returned
777 0 ▶ if($statement =~ m/^Columns:\ (.*)$/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($statement =~ /^Columns:\ (.*)$/mx) 0 0 0
778 0 ($statement,$keys) = $self->_extract_keys_from_columns_header($statement);
779 }
780 0 ▶ if($statement =~ m/^Stats:\ (.*)$/mx or $statement =~ m/^StatsGroupBy:\ (.*)$/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($statement =~ /^Stats:\ (.*)$/mx or $statement =~ /^StatsGroupBy:\ (.*)$/mx) 0 0 0
Condition0%0/3
$statement =~ /^Stats:\ (.*)$/mx or $statement =~ /^StatsGroupBy:\ (.*)$/mx
l!l&&r!l&&!r
000
MC/DC0%0/2
$statement =~ /^Stats:\ (.*)$/mx or $statement =~ /^StatsGroupBy:\ (.*)$/mx
$statement =~ /^Stats:\ (.*)$/mx $statement =~ /^StatsGroupBy:\ (.*)$/mx
Truth table0%0/3
A or B
A= $statement =~ /^Stats:\ (.*)$/mxB= $statement =~ /^StatsGroupBy:\ (.*)$/mx
ABresult
1X1
011
000
781 0 ▶ my $has_columns = defined $keys ? join(",", @{$keys}) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $keys ? : 0 0 0
782 0 ($statement,$keys) = extract_keys_from_stats_statement($statement);
783 0 ▶ unshift @{$keys}, $has_columns if $has_columns;
Branch: 1 branch
BranchTrueFalseTotal
if $has_columns 0 0 0
784 }
785  
786 # Offset header (currently naemon only)
787 0 ▶ if(defined $opt->{'offset'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"offset"}) 0 0 0
788 0 $statement .= "\nOffset: ".$opt->{'offset'};
789 }
790  
791 # Sort header (currently naemon only)
792 0 ▶ if(defined $opt->{'sort'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"sort"}) 0 0 0
793 0 for my $sort (@{$opt->{'sort'}}) {
794 0 $statement .= "\nSort: ".$sort;
795 }
796 }
797  
798 # Commands need no additional header
799 0 ▶ if($statement !~ m/^COMMAND/mx) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($statement =~ /^COMMAND/mx) 0 0 0
800 0 ▶ if($opt->{'wrapped_json'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{'wrapped_json'}) { } 0 0 0
801 0 $header .= "OutputFormat: wrapped_json\n";
802 } else {
803 0 $header .= "OutputFormat: json\n";
804 }
805 0 $header .= "ResponseHeader: fixed16\n";
806 0 ▶ if($self->{'keepalive'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"keepalive"}) 0 0 0
807 0 $header .= "KeepAlive: on\n";
808 }
809 # remove empty lines from statement
810 0 $statement =~ s/\n+/\n/gmx;
811 }
812  
813 # add additional headers
814 0 ▶ if(defined $opt->{'header'} and ref $opt->{'header'} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"header"} and ref $opt->{"header"} eq "HASH") 0 0 0
Condition0%0/3
defined $opt->{"header"} and ref $opt->{"header"} eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $opt->{"header"} and ref $opt->{"header"} eq "HASH"
defined $opt->{"header"} ref $opt->{"header"} eq "HASH"
Truth table0%0/3
A and B
A= defined $opt->{"header"}B= ref $opt->{"header"} eq "HASH"
ABresult
0X0
100
111
815 0 for my $key ( keys %{$opt->{'header'}}) {
816 0 $header .= $key.': '.$opt->{'header'}->{$key}."\n";
817 }
818 }
819  
820 0 chomp($statement);
821 0 my $send = "$statement\n$header";
822 0 ▶ $self->{'logger'}->debug('> '.Dumper($send)) if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
823 0 ($status,$msg,$body) = &_send_socket($self, $send);
824 0 ▶ if($self->{'verbose'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"verbose"}) 0 0 0
825 #$self->{'logger'}->debug("got:");
826 #$self->{'logger'}->debug(Dumper(\@erg));
827 0 $self->{'logger'}->debug('status: '.Dumper($status));
828 0 $self->{'logger'}->debug('msg: '.Dumper($msg));
829 0 $self->{'logger'}->debug('< '.Dumper($body));
830 }
831 }
832  
833 0 ▶ if(!$status || $status >= 300) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $status or $status >= 300) 0 0 0
Condition0%0/3
not $status or $status >= 300
l!l&&r!l&&!r
000
MC/DC0%0/2
not $status or $status >= 300
not $status $status >= 300
Truth table0%0/3
not(A) or B
A= not $statusB= $status >= 300
ABresult
1X1
011
000
834 0 ▶ $body = '' if !defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 0 0 0
835 0 ▶ $status = 300 if !defined $status;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $status 0 0 0
836 0 chomp($body);
837 0 $Monitoring::Livestatus::ErrorCode = $status;
838 0 ▶ if(defined $body and $body ne '') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $body and $body ne '') { } 0 0 0
Condition0%0/3
defined $body and $body ne ""
!ll&&!rl&&r
000
MC/DC0%0/2
defined $body and $body ne ""
defined $body $body ne ""
Truth table0%0/3
A and B
A= defined $bodyB= $body ne ""
ABresult
0X0
100
111
839 0 $Monitoring::Livestatus::ErrorMessage = $body;
840 } else {
841 0 $Monitoring::Livestatus::ErrorMessage = $msg;
842 }
843 0 ▶ $self->{'logger'}->error($status.' - '.$Monitoring::Livestatus::ErrorMessage." in query:\n".$statement) if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
844 0 ▶ if($self->{'errors_are_fatal'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"errors_are_fatal"}) 0 0 0
845 0 confess('ERROR '.$status.' - '.$Monitoring::Livestatus::ErrorMessage." in query:\n".$statement."\n");
846 }
847 0 return;
848 }
849  
850 # return a empty result set if nothing found
851 0 ▶ return({ keys => [], result => []}) if !defined $body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $body 0 0 0
852  
853 # body is already parsed
854 0 my $result;
855 0 ▶ if($status == 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 200) { } 0 0 0
856 0 $result = $body;
857 } else {
858 0 my $json_decoder = Cpanel::JSON::XS->new->utf8->relaxed;
859 # fix json output
860 0 eval {
861 0 $result = $json_decoder->decode($body);
862 };
863 # fix low/high surrogate errors
864 # missing high surrogate character in surrogate pair
865 # surrogate pair expected
866 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
867 # replace u+D800 to u+DFFF (reserved utf-16 low/high surrogates)
868 0 $body =~ s/\\ud[89a-f][0-9a-f]{2}/\\ufffd/gmxio;
869 0 eval {
870 0 $result = $json_decoder->decode($body);
871 };
872 }
873 0 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
874 0 my $message = 'ERROR '.$@." in text: '".$body."'\" for statement: '$statement'\n";
875 0 ▶ $self->{'logger'}->error($message) if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
876 0 ▶ if($self->{'errors_are_fatal'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"errors_are_fatal"}) 0 0 0
877 0 confess($message);
878 }
879 0 return({ keys => [], result => []});
880 }
881 }
882 0 ▶ if(!defined $result) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result) 0 0 0
883 0 my $message = "ERROR undef result for text: '".$body."'\" for statement: '$statement'\n";
884 0 ▶ $self->{'logger'}->error($message) if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
885 0 ▶ if($self->{'errors_are_fatal'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"errors_are_fatal"}) 0 0 0
886 0 confess($message);
887 }
888 0 return({ keys => [], result => []});
889 }
890  
891 # for querys with column header, no separate columns will be returned
892 0 ▶ if(!defined $keys) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $keys) 0 0 0
893 0 ▶ $self->{'logger'}->warn('got statement without Columns: header!') if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
894 0 ▶ if($self->{'warnings'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"warnings"}) 0 0 0
895 0 carp('got statement without Columns: header! -> '.$statement);
896 }
897 0 $keys = shift @{$result};
898 }
899  
900 0 return(&post_processing($self, $result, $opt, $keys));
901 }
902  
903 ########################################
904  
905 =head2 post_processing
906  
907 $ml->post_processing($result, $options, $keys)
908  
909 returns postprocessed result.
910  
911 Useful when using select based io.
912  
913 =cut
914 0 ▶sub post_processing {
Subroutine post_processing: not called CC=8 SCAR=42.8
Pod documented
915 0 my($self, $result, $opt, $keys) = @_;
916  
917 0 my $orig_result;
918 0 ▶ if($opt->{'wrapped_json'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"wrapped_json"}) 0 0 0
919 0 $orig_result = $result;
920 0 $result = delete $orig_result->{'data'};
921 }
922  
923 # add peer information?
924 0 my $with_peers = 0;
925 0 ▶ if(defined $opt->{'addpeer'} and $opt->{'addpeer'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt->{"addpeer"} and $opt->{"addpeer"}) 0 0 0
Condition0%0/3
defined $opt->{"addpeer"} and $opt->{"addpeer"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $opt->{"addpeer"} and $opt->{"addpeer"}
defined $opt->{"addpeer"} $opt->{"addpeer"}
Truth table0%0/3
A and B
A= defined $opt->{"addpeer"}B= $opt->{"addpeer"}
ABresult
0X0
100
111
926 0 $with_peers = 1;
927 }
928  
929 0 ▶ if(defined $with_peers and $with_peers == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $with_peers and $with_peers == 1) 0 0 0
Condition0%0/3
defined $with_peers and $with_peers == 1
!ll&&!rl&&r
000
MC/DC0%0/2
defined $with_peers and $with_peers == 1
defined $with_peers $with_peers == 1
Truth table0%0/3
A and B
A= defined $with_peersB= $with_peers == 1
ABresult
0X0
100
111
930 0 my $peer_name = $self->peer_name;
931 0 my $peer_addr = $self->peer_addr;
932 0 my $peer_key = $self->peer_key;
933  
934 0 unshift @{$keys}, 'peer_name';
935 0 unshift @{$keys}, 'peer_addr';
936 0 unshift @{$keys}, 'peer_key';
937  
938 0 for my $row (@{$result}) {
939 0 unshift @{$row}, $peer_name;
940 0 unshift @{$row}, $peer_addr;
941 0 unshift @{$row}, $peer_key;
942 }
943 }
944  
945 # set some metadata
946 $self->{'meta_data'} = {
947 0 'result_count' => scalar @{$result},
948 };
949 0 ▶ if($opt->{'wrapped_json'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt->{"wrapped_json"}) 0 0 0
950 0 $self->{'meta_data'} = $orig_result;
951 }
952  
953 0 return({ keys => $keys, result => $result });
954 }
955  
956 ########################################
957 0 ▶sub _open {
Subroutine _open: not called CC=7 SCAR=40.3
958 0 my($self) = @_;
959  
960 # return the current socket in keep alive mode
961 0 ▶ if($self->{'keepalive'} and defined $self->{'sock'} and $self->{'sock'}->connected) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"keepalive"} and defined $self->{"sock"} and $self->{"sock"}->connected) 0 0 0
Condition0%0/6
$self->{"keepalive"} and defined $self->{"sock"} and $self->{"sock"}->connected
!ll&&!rl&&r
000
$self->{"keepalive"} and defined $self->{"sock"}
!ll&&!rl&&r
000
MC/DC0%0/3
$self->{"keepalive"} and defined $self->{"sock"} and $self->{"sock"}->connected
$self->{"keepalive"} defined $self->{"sock"} $self->{"sock"}->connected
Truth table0%0/4
A and B and C
A= $self->{"keepalive"}B= defined $self->{"sock"}C= $self->{"sock"}->connected
ABCresult
0XX0
10X0
1100
1111
962 0 ▶ $self->{'logger'}->debug('reusing old connection') if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
963 0 return($self->{'sock'});
964 }
965  
966 0 my $sock = $self->{'CONNECTOR'}->_open();
967  
968 # store socket for later retrieval
969 0 ▶ if($self->{'keepalive'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"keepalive"}) 0 0 0
970 0 $self->{'sock'} = $sock;
971 }
972  
973 0 ▶ $self->{'logger'}->debug('using new connection') if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
974 0 return($sock);
975 }
976  
977 ########################################
978 0 ▶sub _close {
Subroutine _close: not called CC=1 SCAR=6.9
979 0 my($self) = @_;
980 0 my $sock = delete $self->{'sock'};
981 0 return($self->{'CONNECTOR'}->_close($sock));
982 }
983  
984 ########################################
985  
986 =head1 QUERY OPTIONS
987  
988 In addition to the normal query syntax from the livestatus addon, it is
989 possible to set column aliases in various ways.
990  
991 =head2 AddPeer
992  
993 adds the peers name, addr and key to the result set:
994  
995 my $hosts = $ml->selectall_hashref(
996 "GET hosts\nColumns: name alias state",
997 "name",
998 { AddPeer => 1 }
999 );
1000  
1001 =head2 Backend
1002  
1003 send the query only to some specific backends.
1004 Only useful when using multiple backends.
1005  
1006 my $hosts = $ml->selectall_arrayref(
1007 "GET hosts\nColumns: name alias state",
1008 { Backends => [ 'key1', 'key4' ] }
1009 );
1010  
1011 =head2 Columns
1012  
1013 only return the given column indexes
1014  
1015 my $array_ref = $ml->selectcol_arrayref(
1016 "GET hosts\nColumns: name contacts",
1017 { Columns => [2] }
1018 );
1019  
1020 see L<selectcol_arrayref> for more examples
1021  
1022 =head2 Deepcopy
1023  
1024 deep copy/clone the result set.
1025  
1026 Only effective when using multiple backends and threads.
1027 This can be safely turned off if you don't change the
1028 result set.
1029 If you get an error like "Invalid value for shared scalar" error" this
1030 should be turned on.
1031  
1032 my $array_ref = $ml->selectcol_arrayref(
1033 "GET hosts\nColumns: name contacts",
1034 { Deepcopy => 1 }
1035 );
1036  
1037 =head2 Limit
1038  
1039 Just like the Limit: <nr> option from livestatus itself.
1040 In addition you can add a start,length limit.
1041  
1042 my $array_ref = $ml->selectcol_arrayref(
1043 "GET hosts\nColumns: name contacts",
1044 { Limit => "10,20" }
1045 );
1046  
1047 This example will return 20 rows starting at row 10. You will
1048 get row 10-30.
1049  
1050 Cannot be combined with a Limit inside the query
1051 because a Limit will be added automatically.
1052  
1053 Adding a limit this way will greatly increase performance and
1054 reduce memory usage.
1055  
1056 This option is multibackend safe contrary to the "Limit: " part of a statement.
1057 Sending a statement like "GET...Limit: 10" with 3 backends will result in 30 rows.
1058 Using this options, you will receive only the first 10 rows.
1059  
1060 =head2 Rename
1061  
1062 see L<COLUMN ALIAS> for detailed explainaton
1063  
1064 =head2 Slice
1065  
1066 see L<selectall_arrayref> for detailed explainaton
1067  
1068 =head2 Sum
1069  
1070 The Sum option only applies when using multiple backends.
1071 The values from all backends with be summed up to a total.
1072  
1073 my $stats = $ml->selectrow_hashref(
1074 "GET hosts\nStats: state = 0\nStats: state = 1",
1075 { Sum => 1 }
1076 );
1077  
1078 =cut
1079  
1080  
1081 ########################################
1082 # wrapper around _send_socket_do
1083 0 ▶sub _send_socket {
Subroutine _send_socket: not called CC=24 SCAR=64.0
1084 0 my($self, $statement) = @_;
1085  
1086 0 my $retries = 0;
1087 0 my($status, $msg, $recv, $sock);
1088  
1089 # closing a socket sends SIGPIPE to reader
1090 # https://riptutorial.com/posix/example/17424/handle-sigpipe-generated-by-write---in-a-thread-safe-manner
1091 0 local $SIG{PIPE} = 'IGNORE';
1092  
1093 0 ▶ my $maxretries = $ENV{'LIVESTATUS_RETRIES'} // $self->{'retries_on_connection_error'};
Condition0%0/3
$ENV{"LIVESTATUS_RETRIES"} // $self->{"retries_on_connection_error"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$ENV{"LIVESTATUS_RETRIES"} // $self->{"retries_on_connection_error"}
$ENV{"LIVESTATUS_RETRIES"} $self->{"retries_on_connection_error"}
Truth table0%0/3
A // B
A= $ENV{"LIVESTATUS_RETRIES"}B= $self->{"retries_on_connection_error"}
ABresult
1X1
011
000
1094  
1095 # try to avoid connection errors
1096 0 eval {
1097 0 ▶ if($maxretries <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($maxretries <= 0) 0 0 0
1098 0 ($sock, $msg, $recv) = &_send_socket_do($self, $statement);
1099 0 ▶ return($sock, $msg, $recv) if $msg;
Branch: 1 branch
BranchTrueFalseTotal
if $msg 0 0 0
1100 0 ($status, $msg, $recv) = &_read_socket_do($self, $sock, $statement);
1101 0 return($status, $msg, $recv);
1102 }
1103  
1104 0 ▶ while((!defined $status || ($status == 491 || $status == 497 || $status == 500)) && $retries < $maxretries) {
Branch: 1 branch
BranchTrueFalseTotal
if (!defined($status) || ($status == 491 || $status == 497 || $status == 500) and $retries < $maxretries) 0 0 0
Condition0%0/12
!defined($status) || ($status == 491 || $status == 497 || $status == 500) and $retries < $maxretries
!ll&&!rl&&r
000
not defined $status or ($status == 491 or $status == 497 or $status == 500)
l!l&&r!l&&!r
000
$status == 491 or $status == 497 or $status == 500
l!l&&r!l&&!r
000
$status == 491 or $status == 497
l!l&&r!l&&!r
000
MC/DC0%0/5
!defined($status) || ($status == 491 || $status == 497 || $status == 500) and $retries < $maxretries
not defined $status $status == 491 $status == 497 $status == 500 $retries < $maxretries
Truth table0%0/9
not(A) or B or C or D and E
A= not defined $statusB= $status == 491C= $status == 497D= $status == 500E= $retries < $maxretries
ABCDEresult
0000X0
1XXX00
01XX00
001X00
000100
1XXX11
01XX11
001X11
000111
1105 0 $retries++;
1106 0 ($sock, $msg, $recv) = &_send_socket_do($self, $statement);
1107 0 ▶ return($status, $msg, $recv) if $msg;
Branch: 1 branch
BranchTrueFalseTotal
if $msg 0 0 0
1108 0 ($status, $msg, $recv) = &_read_socket_do($self, $sock, $statement);
1109 0 ▶ $self->{'logger'}->debug('query status '.$status) if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1110 0 ▶ if($status == 491 or $status == 497 or $status == 500) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 491 or $status == 497 or $status == 500) 0 0 0
Condition0%0/6
$status == 491 or $status == 497 or $status == 500
l!l&&r!l&&!r
000
$status == 491 or $status == 497
l!l&&r!l&&!r
000
MC/DC0%0/3
$status == 491 or $status == 497 or $status == 500
$status == 491 $status == 497 $status == 500
Truth table0%0/4
A or B or C
A= $status == 491B= $status == 497C= $status == 500
ABCresult
1XX1
01X1
0011
0000
1111 0 ▶ $self->{'logger'}->debug('got status '.$status.' retrying in '.$self->{'retry_interval'}.' seconds') if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1112 0 $self->_close();
1113 0 ▶ sleep($self->{'retry_interval'}) if $retries < $maxretries;
Branch: 1 branch
BranchTrueFalseTotal
if $retries < $maxretries 0 0 0
1114 }
1115 }
1116 };
1117 0 my $err = $@;
1118 0 ▶ if($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
1119 0 ▶ $self->{'logger'}->debug("try 1 failed: $err") if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1120 0 ▶ if($err =~ /broken\ pipe/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err =~ /broken\ pipe/mx) 0 0 0
1121 0 ($sock, $msg, $recv) = &_send_socket_do($self, $statement);
1122 0 ▶ return($status, $msg, $recv) if $msg;
Branch: 1 branch
BranchTrueFalseTotal
if $msg 0 0 0
1123 0 return(&_read_socket_do($self, $sock, $statement));
1124 }
1125 0 ▶ _die_or_confess($err) if $self->{'errors_are_fatal'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"errors_are_fatal"} 0 0 0
1126 }
1127  
1128 0 ▶ $status = $sock unless $status;
Branch: 1 branch
BranchTrueFalseTotal
unless $status 0 0 0
1129 0 $msg =~ s/^$status:\s+//gmx;
1130 0 ▶ _die_or_confess($status.": ".$msg) if($status >= 400 and $self->{'errors_are_fatal'});
Branch: 1 branch
BranchTrueFalseTotal
if $status >= 400 and $self->{"errors_are_fatal"} 0 0 0
Condition0%0/3
$status >= 400 and $self->{"errors_are_fatal"}
!ll&&!rl&&r
000
MC/DC0%0/2
$status >= 400 and $self->{"errors_are_fatal"}
$status >= 400 $self->{"errors_are_fatal"}
Truth table0%0/3
A and B
A= $status >= 400B= $self->{"errors_are_fatal"}
ABresult
0X0
100
111
1131  
1132 0 return($status, $msg, $recv);
1133 }
1134  
1135 ########################################
1136 0 ▶sub _send_socket_do {
Subroutine _send_socket_do: not called CC=6 SCAR=37.4
1137 0 my($self, $statement) = @_;
1138 0 ▶ my $sock = $self->_open() or return(491, $self->_get_error(491, $@ || $!), $@ || $!);
Branch: 1 branch
BranchTrueFalseTotal
my $sock = $self->_open or return 491, $self->_get_error(491, $@ || $!), $@ || $! 0 0 0
Condition0%0/6
$@ || $!
l!l&&r!l&&!r
000
$@ || $!
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ || $!
$@ $!
MC/DC0%0/2
$@ || $!
$@ $!
Truth table0%0/3
A || B
A= $@B= $!
ABresult
1X1
011
000
Truth table0%0/3
A || B
A= $@B= $!
ABresult
1X1
011
000
1139 0 utf8::decode($statement); # make sure
1140 0 utf8::encode($statement); # query is utf8
1141 0 ▶ $sock->printflush($statement,"\n") || return($self->_socket_error($statement, 'write to socket failed'.($! ? ': '.$! : '')));
Branch: 2 branches
BranchTrueFalseTotal
$sock->printflush($statement, "\n") or return $self->_socket_error($statement, 'write to socket failed' . ($! ? ': ' . $! : "")) 0 0 0
$! ? : 0 0 0
1142 0 return $sock;
1143 }
1144  
1145 ########################################
1146 0 ▶sub _read_socket_do {
Subroutine _read_socket_do: not called CC=30 SCAR=68.4
1147 0 my($self, $sock, $statement) = @_;
1148 0 my($recv,$header);
1149  
1150 0 my $s = IO::Select->new();
1151 0 $s->add($sock);
1152  
1153 # COMMAND statements might return a error message
1154 0 ▶ if($statement && $statement =~ m/^COMMAND/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($statement and $statement =~ /^COMMAND/mx) 0 0 0
Condition0%0/3
$statement and $statement =~ /^COMMAND/mx
!ll&&!rl&&r
000
MC/DC0%0/2
$statement and $statement =~ /^COMMAND/mx
$statement $statement =~ /^COMMAND/mx
Truth table0%0/3
A and B
A= $statementB= $statement =~ /^COMMAND/mx
ABresult
0X0
100
111
1155 0 shutdown($sock, 1);
1156 0 ▶ if($s->can_read(3)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($s->can_read(3)) 0 0 0
1157 0 $recv = <$sock>;
1158 }
1159 0 ▶ if($recv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recv) 0 0 0
1160 0 chomp($recv);
1161 0 ▶ if($recv =~ m/^(\d+):\s*(.*)$/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($recv =~ /^(\d+):\s*(.*)$/mx) 0 0 0
1162 0 return($1, $recv, undef);
1163 }
1164 0 return('400', $self->_get_error(400), $recv);
1165 }
1166 0 return('200', $self->_get_error(200), undef);
1167 }
1168  
1169 0 my $timeout = 180;
1170 0 ▶ if($statement) {
Branch: 1 branch
BranchTrueFalseTotal
if ($statement) 0 0 0
1171 # status requests should not take longer than 20 seconds
1172 0 ▶ $timeout = 20 if($statement =~ m/^GET\s+status/mx);
Branch: 1 branch
BranchTrueFalseTotal
if $statement =~ /^GET\s+status/mx 0 0 0
1173 0 ▶ $timeout = 300 if($statement =~ m/^GET\s+log/mx);
Branch: 1 branch
BranchTrueFalseTotal
if $statement =~ /^GET\s+log/mx 0 0 0
1174 }
1175 0 ▶ $timeout = $self->{'query_timeout'} if $self->{'query_timeout'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"query_timeout"} 0 0 0
1176  
1177 0 local $! = undef;
1178 0 my @ready = $s->can_read($timeout);
1179 0 ▶ if(scalar @ready == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @ready == 0) 0 0 0
1180 0 my $err = $!;
1181 0 ▶ if($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
1182 0 return($self->_socket_error($statement, 'socket error '.$err));
1183 }
1184 0 return($self->_socket_error($statement, 'timeout ('.$timeout.'s) while waiting for socket'));
1185 }
1186  
1187 0 ▶ $sock->read($header, 16) || return($self->_socket_error($statement, 'reading header from socket failed'.($! ? ': '.$! : '')));
Branch: 2 branches
BranchTrueFalseTotal
$sock->read($header, 16) or return $self->_socket_error($statement, 'reading header from socket failed' . ($! ? ': ' . $! : "")) 0 0 0
$! ? : 0 0 0
1188 0 ▶ $self->{'logger'}->debug("header: $header") if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1189 0 my($status, $msg, $content_length) = &_parse_header($self, $header, $sock);
1190 0 ▶ return($status, $msg, undef) if !defined $content_length;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content_length 0 0 0
1191 0 our $json_decoder;
1192 0 ▶ if($json_decoder) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Monitoring::Livestatus::json_decoder) { } 0 0 0
1193 0 $json_decoder->incr_reset;
1194 } else {
1195 0 $json_decoder = Cpanel::JSON::XS->new->utf8->relaxed;
1196 }
1197 0 ▶ if($content_length > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_length > 0) 0 0 0
1198 0 ▶ if($status == 200) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status == 200) { } 0 0 0
1199 0 my $remaining = $content_length;
1200 0 my $length = 32768;
1201 0 ▶ if($remaining < $length) { $length = $remaining; }
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining < $length) 0 0 0
1202 0 ▶ while($length > 0 && $sock->read(my $buf, $length)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($length > 0 and $sock->read(my $buf, $length)) 0 0 0
Condition0%0/3
$length > 0 and $sock->read(my $buf, $length)
!ll&&!rl&&r
000
MC/DC0%0/2
$length > 0 and $sock->read(my $buf, $length)
$length > 0 $sock->read(my $buf, $length)
Truth table0%0/3
A and B
A= $length > 0B= $sock->read(my $buf, $length)
ABresult
0X0
100
111
1203 # replace u+D800 to u+DFFF (reserved utf-16 low/high surrogates)
1204 0 $buf =~ s/\\ud[89a-f][0-9a-f]{2}/\\ufffd/gmxio;
1205 0 $json_decoder->incr_parse($buf);
1206 0 $remaining = $remaining -$length;
1207 0 ▶ if($remaining < $length) { $length = $remaining; }
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining < $length) 0 0 0
1208 }
1209 0 ▶ $recv = $json_decoder->incr_parse or return($self->_socket_error($statement, 'reading remaining '.$length.' bytes from socket failed'.($! ? ': '.$! : '')));
Branch: 2 branches
BranchTrueFalseTotal
$recv = $Monitoring::Livestatus::json_decoder->incr_parse or return $self->_socket_error($statement, 'reading remaining ' . $length . ' bytes from socket failed' . ($! ? ': ' . $! : "")) 0 0 0
$! ? : 0 0 0
1210 0 $json_decoder->incr_reset;
1211 } else {
1212 0 ▶ $sock->read($recv, $content_length) or return($self->_socket_error($statement, 'reading body from socket failed'.($! ? ': '.$! : '')));
Branch: 2 branches
BranchTrueFalseTotal
$sock->read($recv, $content_length) or return $self->_socket_error($statement, 'reading body from socket failed' . ($! ? ': ' . $! : "")) 0 0 0
$! ? : 0 0 0
1213 }
1214 }
1215  
1216 0 ▶ $self->_close() unless $self->{'keepalive'};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"keepalive"} 0 0 0
1217 0 ▶ if($status >= 400 && $recv) {
Branch: 1 branch
BranchTrueFalseTotal
if ($status >= 400 and $recv) 0 0 0
Condition0%0/3
$status >= 400 and $recv
!ll&&!rl&&r
000
MC/DC0%0/2
$status >= 400 and $recv
$status >= 400 $recv
Truth table0%0/3
A and B
A= $status >= 400B= $recv
ABresult
0X0
100
111
1218 0 $msg .= ' - '.$recv;
1219 }
1220 0 return($status, $msg, $recv);
1221 }
1222  
1223 ########################################
1224 0 ▶sub _socket_error {
Subroutine _socket_error: not called CC=5 SCAR=34.0
1225 0 my($self, $statement, $err) = @_;
1226  
1227 0 my $message = "\n";
1228 0 $message .= "peer ".Dumper($self->peer_name);
1229 0 $message .= "statement ".Dumper($statement);
1230  
1231 0 ▶ $self->{'logger'}->error($message) if $self->{'verbose'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"verbose"} 0 0 0
1232  
1233 0 ▶ if($self->{'retries_on_connection_error'} <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"retries_on_connection_error"} <= 0) 0 0 0
1234 0 ▶ if($self->{'errors_are_fatal'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'errors_are_fatal'}) { } 0 0 0
1235 0 _die_or_confess($message);
1236 }
1237 else {
1238 0 carp($message);
1239 }
1240 }
1241 0 $self->_close();
1242 0 ▶ return(500, $self->_get_error(500).($err ? " - ".$err : ""), $message);
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 0 0 0
1243 }
1244  
1245 ########################################
1246 1 ▶sub _parse_header {
Subroutine _parse_header: called CC=4 SCAR=15.0
1247 1 my($self, $header, $sock) = @_;
1248  
1249 1 ▶ if(!defined $header) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $header) 0 1 1
1250 0 return(497, $self->_get_error(497), undef);
1251 }
1252  
1253 1 my $headerlength = length($header);
1254 1 ▶ if($headerlength != 16) {
Branch: 1 branch
BranchTrueFalseTotal
if ($headerlength != 16) 0 1 1
1255 0 return(498, $self->_get_error(498)."\ngot: ".$header.<$sock>, undef);
1256 }
1257 1 chomp($header);
1258  
1259 1 my $status = substr($header,0,3);
1260 1 my $content_length = substr($header,5);
1261 1 ▶ if($content_length !~ m/^\s*(\d+)$/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $content_length =~ /^\s*(\d+)$/mx) { } 0 1 1
1262 0 return(499, $self->_get_error(499)."\ngot: ".$header.<$sock>, undef);
1263 } else {
1264 1 $content_length = $1;
1265 }
1266  
1267 1 return($status, $self->_get_error($status), $content_length);
1268 }
1269  
1270 ########################################
1271  
1272 =head1 COLUMN ALIAS
1273  
1274 In addition to the normal query syntax from the livestatus addon, it is
1275 possible to set column aliases in various ways.
1276  
1277 A valid Columns: Header could look like this:
1278  
1279 my $hosts = $ml->selectall_arrayref(
1280 "GET hosts\nColumns: state as status"
1281 );
1282  
1283 Stats queries could be aliased too:
1284  
1285 my $stats = $ml->selectall_arrayref(
1286 "GET hosts\nStats: state = 0 as up"
1287 );
1288  
1289 This syntax is available for: Stats, StatsAnd, StatsOr and StatsGroupBy
1290  
1291  
1292 An alternative way to set column aliases is to define rename option key/value
1293 pairs:
1294  
1295 my $hosts = $ml->selectall_arrayref(
1296 "GET hosts\nColumns: name", {
1297 rename => { 'name' => 'hostname' }
1298 }
1299 );
1300  
1301 =cut
1302  
1303 ########################################
1304  
1305 =head2 extract_keys_from_stats_statement
1306  
1307 extract_keys_from_stats_statement($statement)
1308  
1309 Extract column keys from statement.
1310  
1311 =cut
1312 2 ▶sub extract_keys_from_stats_statement {
Subroutine extract_keys_from_stats_statement: called CC=15 SCAR=27.5
Pod documented
1313 2 my($statement) = @_;
1314  
1315 2 my(@header, $new_statement);
1316  
1317 2 for my $line (split/\n/mx, $statement) {
1318 44 ▶ if(substr($line, 0, 5) ne 'Stats') { # faster shortcut for non-stats lines
Branch: 1 branch
BranchTrueFalseTotal
if (substr($line, 0, 5) ne "Stats") 2 42 44
1319 2 $new_statement .= $line."\n";
1320 2 next;
1321 }
1322 42 ▶ if($line =~ m/^Stats:\ (.*)\s+as\s+(.*?)$/mxo) {
Branch: 8 branches
BranchTrueFalseTotal
if ($line =~ /^Stats:\ (.*)\s+as\s+(.*?)$/mox) { } 5 37 42
elsif ($line =~ /^Stats:\ (.*)$/mox) { } 27 10 37
elsif ($line =~ /^StatsAnd:\ (\d+)\s+as\s+(.*?)$/mox) { } 4 6 10
elsif ($line =~ /^StatsAnd:\ (\d+)$/mox) { } 4 2 6
elsif ($line =~ /^StatsOr:\ (\d+)\s+as\s+(.*?)$/mox) { } 1 1 2
elsif ($line =~ /^StatsOr:\ (\d+)$/mox) { } 1 0 1
elsif ($line =~ /^StatsGroupBy:\ (.*)\s+as\s+(.*?)$/mox) { } 0 0 0
elsif ($line =~ /^StatsGroupBy:\ (.*)$/mox) { } 0 0 0
1323 5 push @header, $2;
1324 5 $line = 'Stats: '.$1;
1325 }
1326 elsif($line =~ m/^Stats:\ (.*)$/mxo) {
1327 27 push @header, $1;
1328 }
1329  
1330 elsif($line =~ m/^StatsAnd:\ (\d+)\s+as\s+(.*?)$/mxo) {
1331 4 ▶ for(my $x = 0; $x < $1; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $1) 9 4 13
1332 9 pop @header;
1333 }
1334 4 $line = 'StatsAnd: '.$1;
1335 4 push @header, $2;
1336 }
1337 elsif($line =~ m/^StatsAnd:\ (\d+)$/mxo) {
1338 4 my @to_join;
1339 4 ▶ for(my $x = 0; $x < $1; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $1) 9 4 13
1340 9 unshift @to_join, pop @header;
1341 }
1342 4 push @header, join(' && ', @to_join);
1343 }
1344  
1345 elsif($line =~ m/^StatsOr:\ (\d+)\s+as\s+(.*?)$/mxo) {
1346 1 ▶ for(my $x = 0; $x < $1; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $1) 2 1 3
1347 2 pop @header;
1348 }
1349 1 $line = 'StatsOr: '.$1;
1350 1 push @header, $2;
1351 }
1352 elsif($line =~ m/^StatsOr:\ (\d+)$/mxo) {
1353 1 my @to_join;
1354 1 ▶ for(my $x = 0; $x < $1; $x++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($x < $1) 2 1 3
1355 2 unshift @to_join, pop @header;
1356 }
1357 1 push @header, join(' || ', @to_join);
1358 }
1359  
1360 # StatsGroupBy header are always sent first
1361 elsif($line =~ m/^StatsGroupBy:\ (.*)\s+as\s+(.*?)$/mxo) {
1362 0 unshift @header, $2;
1363 0 $line = 'StatsGroupBy: '.$1;
1364 }
1365 elsif($line =~ m/^StatsGroupBy:\ (.*)$/mxo) {
1366 0 unshift @header, $1;
1367 }
1368 42 $new_statement .= $line."\n";
1369 }
1370  
1371 2 return($new_statement, \@header);
1372 }
1373  
1374 ########################################
1375 1 ▶sub _extract_keys_from_columns_header {
Subroutine _extract_keys_from_columns_header: called CC=5 SCAR=16.1
1376 1 my($self, $statement) = @_;
1377  
1378 1 my(@header, $new_statement);
1379 1 for my $line (split/\n/mx, $statement) {
1380 2 ▶ if($line =~ m/^Columns:\s+(.*)$/mx) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^Columns:\s+(.*)$/mx) 1 1 2
1381 1 for my $column (split/\s+/mx, $1) {
1382 8 ▶ if($column eq 'as') {
Branch: 1 branch
BranchTrueFalseTotal
if ($column eq 'as') { } 2 6 8
1383 2 pop @header;
1384 } else {
1385 6 push @header, $column;
1386 }
1387 }
1388 1 $line =~ s/\s+as\s+([^\s]+)/\ /gmx;
1389 }
1390 2 $new_statement .= $line."\n";
1391 }
1392  
1393 1 return($new_statement, \@header);
1394 }
1395  
1396 ########################################
1397  
1398 =head1 ERROR HANDLING
1399  
1400 Errorhandling can be done like this:
1401  
1402 use Monitoring::Livestatus;
1403 my $ml = Monitoring::Livestatus->new(
1404 socket => '/var/lib/livestatus/livestatus.sock'
1405 );
1406 $ml->errors_are_fatal(0);
1407 my $hosts = $ml->selectall_arrayref("GET hosts");
1408 if($Monitoring::Livestatus::ErrorCode) {
1409 confess($Monitoring::Livestatus::ErrorMessage);
1410 }
1411  
1412 =cut
1413 1 ▶sub _get_error {
Subroutine _get_error: called CC=3 SCAR=11.2
1414 1 my($self, $code, $append) = @_;
1415  
1416 1 my $codes = {
1417 '200' => 'OK. Reponse contains the queried data.',
1418 '201' => 'COMMANDs never return something',
1419 '400' => 'The request contains an invalid header.',
1420 '401' => 'The request contains an invalid header.',
1421 '402' => 'The request is completely invalid.',
1422 '403' => 'The request is incomplete.',
1423 '404' => 'The target of the GET has not been found (e.g. the table).',
1424 '405' => 'A non-existing column was being referred to',
1425 '413' => 'Maximum response size reached',
1426 '452' => 'internal livestatus error',
1427 '490' => 'no query',
1428 '491' => 'failed to connect',
1429 '492' => 'Separators not allowed in statement. Please use the separator options in new()',
1430 '493' => 'OuputFormat not allowed in statement. Header will be set automatically',
1431 '494' => 'ColumnHeaders not allowed in statement. Header will be set automatically',
1432 '495' => 'ResponseHeader not allowed in statement. Header will be set automatically',
1433 '496' => 'Keepalive not allowed in statement. Please use the keepalive option in new()',
1434 '497' => 'got no header',
1435 '498' => 'header is not exactly 16byte long',
1436 '499' => 'not a valid header (no content-length)',
1437 '500' => 'socket error',
1438 '502' => 'backend connection proxy error',
1439 };
1440  
1441 1 ▶ confess('non existant error code: '.$code) if !defined $codes->{$code};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $codes->{$code} 0 1 1
1442 1 my $msg = $codes->{$code};
1443 1 ▶ $msg .= ' - '.$append if $append;
Branch: 1 branch
BranchTrueFalseTotal
if $append 0 1 1
1444  
1445 1 return($msg);
1446 }
1447  
1448 ########################################
1449 24 ▶sub _get_peer {
Subroutine _get_peer: called CC=20 SCAR=43.4
1450 24 my($self) = @_;
1451  
1452 # check if the supplied peer is a socket or a server address
1453 24 ▶ if(defined $self->{'peer'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"peer"}) 21 3 24
1454 21 ▶ if(ref $self->{'peer'} eq '') {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $self->{'peer'} eq '') { } 17 4 21
elsif (ref $self->{'peer'} eq 'ARRAY') { } 4 0 4
elsif (ref $self->{'peer'} eq 'HASH') { } 0 0 0
1455 17 ▶ my $name = $self->{'name'} || ''.$self->{'peer'};
Condition66%2/3
$self->{'name'} || '' . $self->{'peer'}
l!l&&r!l&&!r
1250
MC/DC0%0/2
$self->{'name'} || '' . $self->{'peer'}
$self->{'name'} '' . $self->{'peer'}
Truth table66%2/3
A || B
A= $self->{'name'}B= '' . $self->{'peer'}
ABresult
1X1
011
000
1456 17 ▶ if(index($self->{'peer'}, ':') > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($self->{'peer'}, ':') > 0) { } 5 12 17
1457 5 return({ 'peer' => ''.$self->{'peer'}, type => 'INET', name => $name });
1458 } else {
1459 12 return({ 'peer' => ''.$self->{'peer'}, type => 'UNIX', name => $name });
1460 }
1461 }
1462 elsif(ref $self->{'peer'} eq 'ARRAY') {
1463 4 for my $peer (@{$self->{'peer'}}) {
1464 4 ▶ if(ref $peer eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $peer eq 'HASH') { } 0 4 4
1465 0 ▶ next if !defined $peer->{'peer'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $peer->{"peer"} 0 0 0
1466 0 ▶ $peer->{'name'} = ''.$peer->{'peer'} unless defined $peer->{'name'};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $peer->{"name"} 0 0 0
1467 0 ▶ if(!defined $peer->{'type'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $peer->{"type"}) 0 0 0
1468 0 $peer->{'type'} = 'UNIX';
1469 0 ▶ if(index($peer->{'peer'}, ':') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($peer->{"peer"}, ":") != -1) 0 0 0
1470 0 $peer->{'type'} = 'INET';
1471 }
1472 }
1473 0 return $peer;
1474 } else {
1475 4 my $type = 'UNIX';
1476 4 ▶ if(index($peer, ':') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($peer, ":") != -1) 0 4 4
1477 0 $type = 'INET';
1478 }
1479 4 return({ 'peer' => ''.$peer, type => $type, name => ''.$peer });
1480 }
1481 }
1482 }
1483 elsif(ref $self->{'peer'} eq 'HASH') {
1484 0 for my $peer (keys %{$self->{'peer'}}) {
1485 0 my $name = $self->{'peer'}->{$peer};
1486 0 my $type = 'UNIX';
1487 0 ▶ if(index($peer, ':') >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($peer, ":") != -1) 0 0 0
1488 0 $type = 'INET';
1489 }
1490 0 return({ 'peer' => ''.$peer, type => $type, name => ''.$name });
1491 }
1492 } else {
1493 0 confess('type '.(ref $self->{'peer'}).' is not supported for peer option');
1494 }
1495 }
1496 3 ▶ if(defined $self->{'socket'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"socket"}) 2 1 3
1497 2 ▶ my $name = $self->{'name'} || ''.$self->{'socket'};
Condition33%1/3
$self->{'name'} || '' . $self->{'socket'}
l!l&&r!l&&!r
020
MC/DC0%0/2
$self->{'name'} || '' . $self->{'socket'}
$self->{'name'} '' . $self->{'socket'}
Truth table33%1/3
A || B
A= $self->{'name'}B= '' . $self->{'socket'}
ABresult
1X1
011
000
1498 2 return({ 'peer' => ''.$self->{'socket'}, type => 'UNIX', name => $name });
1499 }
1500 1 ▶ if(defined $self->{'server'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"server"}) 1 0 1
1501 1 ▶ my $name = $self->{'name'} || ''.$self->{'server'};
Condition33%1/3
$self->{'name'} || '' . $self->{'server'}
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->{'name'} || '' . $self->{'server'}
$self->{'name'} '' . $self->{'server'}
Truth table33%1/3
A || B
A= $self->{'name'}B= '' . $self->{'server'}
ABresult
1X1
011
000
1502 1 return({ 'peer' => ''.$self->{'server'}, type => 'INET', name => $name });
1503 }
1504  
1505 # check if we got a peer
1506 0 confess('please specify a peer');
1507 }
1508  
1509  
1510 ########################################
1511 0 ▶sub _lowercase_and_verify_options {
Subroutine _lowercase_and_verify_options: not called CC=6 SCAR=37.4
1512 0 my($self, $opts) = @_;
1513 0 my $return = {};
1514  
1515 # make keys lowercase
1516 0 %{$return} = map { lc($_) => $opts->{$_} } keys %{$opts};
1517  
1518 0 ▶ if($self->{'warnings'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"warnings"}) 0 0 0
1519 0 for my $key (keys %{$return}) {
1520 0 ▶ if(!defined $allowed_options->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $allowed_options->{$key}) 0 0 0
1521 0 carp("unknown option used: $key - please use only: ".join(', ', keys %{$allowed_options}));
1522 }
1523 }
1524 }
1525  
1526 # set limits
1527 0 ▶ if(defined $return->{'limit'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $return->{"limit"}) 0 0 0
1528 0 ▶ if(index($return->{'limit'}, ',') != -1) {
Branch: 1 branch
BranchTrueFalseTotal
if (index($return->{'limit'}, ',') != -1) { } 0 0 0
1529 0 my($limit_start,$limit_length) = split /,/mx, $return->{'limit'};
1530 0 $return->{'limit_start'} = $limit_start;
1531 0 $return->{'limit_length'} = $limit_length;
1532 }
1533 else {
1534 0 $return->{'limit_start'} = 0;
1535 0 $return->{'limit_length'} = $return->{'limit'};
1536 }
1537 0 delete $return->{'limit'};
1538 }
1539  
1540 0 return($return);
1541 }
1542  
1543 ########################################
1544 0 ▶sub _log_statement {
Subroutine _log_statement: not called CC=1 SCAR=6.9
1545 0 my($self, $statement, $opt, $limit) = @_;
1546 0 my $d = Data::Dumper->new([$opt]);
1547 0 $d->Indent(0);
1548 0 my $optstring = $d->Dump;
1549 0 $optstring =~ s/^\$VAR1\s+=\s+//mx;
1550 0 $optstring =~ s/;$//mx;
1551  
1552 # remove empty lines from statement
1553 0 $statement =~ s/\n+/\n/gmx;
1554  
1555 0 my $cleanstatement = $statement;
1556 0 $cleanstatement =~ s/\n/\\n/gmx;
1557 0 $self->{'logger'}->debug('selectall_arrayref("'.$cleanstatement.'", '.$optstring.', '.$limit.')');
1558 0 return 1;
1559 }
1560  
1561 ########################################
1562 0 ▶sub _die_or_confess {
Subroutine _die_or_confess: not called CC=2 SCAR=17.9
1563 0 my($msg) = @_;
1564 0 my @lines = split/\n/mx, $msg;
1565 0 ▶ if(scalar @lines > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @lines > 2) 0 0 0
1566 0 die($msg);
1567 }
1568 0 confess($msg);
1569 }
1570  
1571 ########################################
1572  
1573 4 1;
1574  
1575 =head1 SEE ALSO
1576  
1577 For more information about the query syntax and the livestatus plugin installation
1578 see the Livestatus page: http://mathias-kettner.de/checkmk_livestatus.html
1579  
1580 =head1 AUTHOR
1581  
1582 Sven Nierlein, 2009-present, <sven@nierlein.org>
1583  
1584 =head1 COPYRIGHT AND LICENSE
1585  
1586 Copyright (C) by Sven Nierlein
1587  
1588 This library is free software; you can redistribute it and/or modify
1589 it under the same terms as Perl itself.
1590  
1591 =cut
1592  
1593 __END__
↑ Summary Livestatus/INET.pm »