blib/lib/Monitoring/Sneck/Checks/base.pm

filter: Statementstmt 96.1% 296 / 308 Branchbran 86.9% 127 / 146 Conditioncond 78.5% 77 / 98 MC/DCmcdc 60.7% 34 / 56 Subroutinesub 98.1% 52 / 53 Podpod 100% 39 / 39 totaltotal 89.2% 625 / 700 CC 116 SCAR 19.4
CC
116
Cov
91%
expect_met
16.1
parse_args
16.0
parse_range
12.1
CRAP 7.0
« blib/lib/Monitoring/Sneck/Checks/service.pm ↑ Summary blib/lib/Monitoring/Sneck/Checks.pm »
1 package Monitoring::Sneck::Checks::base;
2  
3 292 ▶use 5.014;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 292 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 292 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 292 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 292 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 292 ▶use IO::Select ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 292 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 292 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 =head1 NAME
13  
14 Monitoring::Sneck::Checks::base - what Monitoring::Sneck::Checks checks are built on
15  
16 =head1 VERSION
17  
18 Version 0.0.1
19  
20 =cut
21  
22 292 our $VERSION = '0.0.1';
23  
24 292 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
25 292 OK => 0,
26 WARNING => 1,
27 CRITICAL => 2,
28 UNKNOWN => 3,
29 292 };
30  
31 # Status names, by code.
32 292 our @STATUS_NAMES = ( 'OK', 'WARNING', 'CRITICAL', 'UNKNOWN' );
33  
34 # How bad each code is, for worst. CRITICAL, then WARNING, then UNKNOWN.
35 292 our %SEVERITY = ( 0 => 0, 3 => 1, 1 => 2, 2 => 3 );
36  
37 # A number in a range or option, such as 10, -2, or 0.5.
38 292 our $NUMBER = qr/-?(?:[0-9]+\.?[0-9]*|\.[0-9]+)/;
39  
40 # The OS, as in $^O, for checks that read it differently per OS. Set by tests.
41 292 our $OS = $^O;
42  
43 # Where Linux's proc file system is. Set by tests.
44 292 our $PROC = '/proc';
45  
46 # How each comparison of a expect is put in messages, before the value wanted.
47 292 our %EXPECT_WORDS
48 = ( '=' => '', '!=' => 'anything but ', '<' => 'under ', '<=' => 'at most ', '>' => 'over ', '>=' => 'at least ' );
49  
50 # Where checks keep state between runs. Set by tests.
51 292 our $STATE_DIR = '/var/cache/sneck.checks';
52  
53 =head1 SYNOPSIS
54  
55 package Monitoring::Sneck::Checks::example;
56  
57 use strict;
58 use warnings;
59 use parent 'Monitoring::Sneck::Checks::base';
60  
61 sub option_spec { return ( 'file|f=s', 'warning|w=s', 'critical|c=s' ) }
62 sub defaults { return { warning => '10', critical => '20' } }
63 sub required { return ('file') }
64 sub ranges { return ( 'warning', 'critical' ) }
65  
66 sub check {
67 my ($self) = @_;
68  
69 my @lines = split( /\n/, ... );
70 my $code = $self->threshold_status( scalar(@lines), $self->opt('warning'), $self->opt('critical') );
71 $self->perfdata( label => 'lines', value => scalar(@lines), warning => $self->opt('warning') );
72  
73 return $self->finish( $code, scalar(@lines) . ' lines in ' . $self->opt('file') );
74 }
75  
76 1;
77  
78 =head1 WRITING A CHECK
79  
80 A check is a subclass named Monitoring::Sneck::Checks::$name. It is
81 made by L</new>, which parses its args, and then L</check> is called,
82 which returns the code. Those it may provide are below. Only check is
83 needed.
84  
85 - check :: Does the check. Returns OK, WARNING, CRITICAL, or UNKNOWN,
86 usually through L</finish>. Dying is UNKNOWN.
87  
88 - option_spec :: The options it takes, as a list of L<Getopt::Long>
89 specs. The first name of each is what L</opt> knows it by.
90 -t and --timeout are added.
91  
92 - defaults :: A hash ref of defaults for its options.
93  
94 - required :: A list of the options that must be given.
95  
96 - ranges :: A list of the options that are ranges, see L</RANGES>,
97 checked by new.
98  
99 - validate :: Given the hash ref of options, returns a list of what is
100 wrong with them, for what option_spec and ranges can not catch.
101  
102 - label :: What starts its output, such as HTTP. The upper cased name
103 by default.
104  
105 Output is written through L</out> and L</err>, not print, which keeps
106 the order of the two. Anything printed is caught as well, so it never
107 ends up in sneck's own output. A check must not exit, as it runs inside
108 sneck.
109  
110 Modules only some checks use should be loaded with require in the
111 check, as every check runs in the same process.
112  
113 =head1 COMMON OPTIONS
114  
115 - -t, --timeout :: Seconds to wait on the network. Each lookup or
116 connection gets this, not the check as a whole.
117 Default :: a second under what it is run with, and at least one
118  
119 =head1 RANGES
120  
121 Thresholds are nagios style ranges. A value outside of the range
122 alerts, or inside of it if it starts with @.
123  
124 - 10 :: Under 0 or over 10.
125  
126 - 10: :: Under 10.
127  
128 - ~:10 :: Over 10, ~ being negative infinity.
129  
130 - 10:20 :: Under 10 or over 20.
131  
132 - @10:20 :: 10 to 20.
133  
134 =head1 METHODS
135  
136 =head2 new
137  
138 Makes the check and parses its args. Dies on bad args, which is
139 UNKNOWN.
140  
141 - args :: Array ref of args, or a string of them.
142 Default :: []
143  
144 - timeout :: Seconds it is run with.
145 Default :: 30
146  
147 my $check = Monitoring::Sneck::Checks::http->new( args => [ '-H', 'www.example.org' ], timeout => 30 );
148  
149 =cut
150  
151 3523 ▶sub new {
Subroutine new: called CC=3 SCAR=11.0
Pod documented
152 3523 my ( $class, %opts ) = @_;
153  
154 my $self = bless(
155 {
156 3523 ▶ run_timeout => $opts{timeout} // 30,
Condition100%2/2
$opts{"timeout"} // 30
l!l
35149
MC/DC100%1/1
$opts{"timeout"} // 30
$opts{"timeout"}
Truth table100%2/2
A
A= $opts{"timeout"}
Aresult
11
00
157 options => {},
158 perfdata => [],
159 stdout => '',
160 stderr => '',
161 combined => '',
162 },
163 $class
164 );
165 3523 ▶ $self->{options} = $self->parse_args( $opts{args} // [] );
Condition100%2/2
$opts{"args"} // []
l!l
35194
MC/DC100%1/1
$opts{"args"} // []
$opts{"args"}
Truth table100%2/2
A
A= $opts{"args"}
Aresult
11
00
166  
167 3288 return $self;
168 } ## end sub new
169  
170 =head2 parse_args
171  
172 Parses args as said by option_spec, defaults, required, and ranges.
173 Used by new. Dies listing every problem.
174  
175 - args :: Array ref of args, or a string of them, which L<Getopt::Long>
176 splits like a shell would. A string with unbalanced quotes dies.
177  
178 Returns a hash ref of option names to values.
179  
180 my $options = $check->parse_args( [ '-H', 'www.example.org', '-w', '2' ] );
181 my $options = $check->parse_args(q{-H www.example.org -s 'Welcome home'});
182  
183 =cut
184  
185 3523 ▶sub parse_args {
Subroutine parse_args: called CC=16 SCAR=27.7
Pod documented
186 3523 my ( $self, $args ) = @_;
187  
188 3523 ▶ if ( !ref($args) && !$self->quotes_balanced($args) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $args or $self->quotes_balanced($args)) 3 3520 3523
Condition100%3/3
ref $args or $self->quotes_balanced($args)
l!l&&r!l&&!r
351463
MC/DC100%2/2
ref $args or $self->quotes_balanced($args)
ref $args $self->quotes_balanced($args)
Truth table100%3/3
A or B
A= ref $argsB= $self->quotes_balanced($args)
ABresult
1X1
011
000
189 3 die("args have unbalanced quotes\n");
190 }
191  
192 3520 my @problems;
193 my %parsed;
194 3520 my @left;
195 {
196 3520 ▶ local $SIG{__WARN__} = sub { my $problem = $_[0]; $problem =~ s/\s+\z//; push( @problems, $problem ) };
Subroutine __ANON__: called CC=1 SCAR=0.0
197 3520 my $saved_config = Getopt::Long::Configure( 'bundling', 'no_ignore_case', 'no_auto_abbrev', 'permute' );
198 3520 ▶ if ( ref($args) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args eq 'ARRAY') { } 3514 6 3520
199 3514 @left = @{$args};
200 3514 Getopt::Long::GetOptionsFromArray( \@left, \%parsed, 'timeout|t=s', $self->option_spec );
201 } else {
202 6 my ( $parsed_ok, $rest )
203 = Getopt::Long::GetOptionsFromString( $args, \%parsed, 'timeout|t=s', $self->option_spec );
204 6 @left = @{$rest};
205 }
206 3520 Getopt::Long::Configure($saved_config);
207 } ## end block
208 3520 foreach my $left (@left) {
209 11 push( @problems, 'unexpected arg "' . $left . '"' );
210 }
211  
212 3520 my %options = ( %{ $self->defaults }, %parsed );
213 3520 foreach my $name ( $self->required ) {
214 410 ▶ if ( !defined( $options{$name} ) || ( ref( $options{$name} ) eq 'ARRAY' && !defined( $options{$name}[0] ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $options{$name} or ref $options{$name} eq "ARRAY" and not defined $options{$name}[0]) 13 397 410
Condition66%4/6
not defined $options{$name} or ref $options{$name} eq "ARRAY" and not defined $options{$name}[0]
l!l&&r!l&&!r
130397
ref $options{$name} eq "ARRAY" and not defined $options{$name}[0]
!ll&&!rl&&r
1852120
MC/DC33%1/3
not defined $options{$name} or ref $options{$name} eq "ARRAY" and not defined $options{$name}[0]
not defined $options{$name} ref $options{$name} eq "ARRAY" not defined $options{$name}[0]
Truth table75%3/4
not(A) or B and not(C)
A= not defined $options{$name}B= ref $options{$name} eq "ARRAY"C= not defined $options{$name}[0]
ABCresult
1XX1
0111
00X0
0100
215 13 push( @problems, '--' . $name . ' is required' );
216 }
217 }
218 3520 ▶ if ( defined( $options{timeout} ) && ( $options{timeout} !~ /\A$NUMBER\z/ || $options{timeout} <= 0 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options{"timeout"} and !($options{"timeout"} =~ /\A$Monitoring::Sneck::Checks::base::NUMBER\z/u) || $options{"timeout"} <= 0) 1 3519 3520
Condition83%5/6
defined $options{"timeout"} and !($options{"timeout"} =~ /\A$Monitoring::Sneck::Checks::base::NUMBER\z/u) || $options{"timeout"} <= 0
!ll&&!rl&&r
351271
not $options{"timeout"} =~ /\A$Monitoring::Sneck::Checks::base::NUMBER\z/u or $options{"timeout"} <= 0
l!l&&r!l&&!r
017
MC/DC66%2/3
defined $options{"timeout"} and !($options{"timeout"} =~ /\A$Monitoring::Sneck::Checks::base::NUMBER\z/u) || $options{"timeout"} <= 0
defined $options{"timeout"} not $options{"timeout"} =~ /\A$Monitoring::Sneck::Checks::base::NUMBER\z/u $options{"timeout"} <= 0
Truth table75%3/4
A and not(B) or C
A= defined $options{"timeout"}B= not $options{"timeout"} =~ /\A$Monitoring::Sneck::Checks::base::NUMBER\z/uC= $options{"timeout"} <= 0
ABCresult
0XX0
1000
11X1
1011
219 1 push( @problems, '--timeout must be a number over 0' );
220 }
221 3520 foreach my $name ( $self->ranges ) {
222 7237 ▶ if ( defined( $options{$name} ) && !eval { $self->parse_range( $options{$name} ); 1 } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options{$name} and not eval { do { $self->parse_range($options{$name}); 1 } }) 7 7230 7237
Condition100%3/3
defined $options{$name} and not eval { do { $self->parse_range($options{$name}); 1 } }
!ll&&!rl&&r
393732937
MC/DC100%2/2
defined $options{$name} and not eval { do { $self->parse_range($options{$name}); 1 } }
defined $options{$name} not eval { do { $self->parse_range($options{$name}); 1 } }
Truth table100%3/3
A and not(B)
A= defined $options{$name}B= not eval { do { $self->parse_range($options{$name}); 1 } }
ABresult
0X0
100
111
223 7 my $problem = $@;
224 7 $problem =~ s/\s+\z//;
225 7 push( @problems, '--' . $name . ' ' . $problem );
226 }
227 }
228 3520 push( @problems, $self->validate( \%options ) );
229 3520 ▶ die( join( ', ', @problems ) . "\n" ) if defined( $problems[0] );
Branch: 1 branch
BranchTrueFalseTotal
if defined $problems[0] 232 3288 3520
230  
231 3288 return \%options;
232 } ## end sub parse_args
233  
234 =head2 quotes_balanced
235  
236 Returns 1 if every ' and " in the text is closed, else 0. A backslash
237 escapes the next character, in or out of quotes, the same as
238 L<Getopt::Long> splitting a string goes by.
239  
240 $check->quotes_balanced(q{-s 'Welcome home'}); # 1
241 $check->quotes_balanced(q{-s 'Welcome}); # 0
242 $check->quotes_balanced(q{-s "it's"}); # 1
243  
244 =cut
245  
246 20 ▶sub quotes_balanced {
Subroutine quotes_balanced: called CC=3 SCAR=11.0
Pod documented
247 20 my ( $self, $text ) = @_;
248  
249 # eat unquoted runs, escaped characters, and whole quoted parts, until something does not close
250 20 my $balanced_to = 0;
251 20 ▶ while ( $text =~ /\G(?:[^'"\\]+|\\.|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/gcs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /\G(?:[^'"\\]+|\\.|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/cgsu) 34 20 54
252 34 $balanced_to = pos($text);
253 }
254  
255 20 ▶ return $balanced_to == length($text) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$balanced_to == length $text ? : 13 7 20
256 } ## end sub quotes_balanced
257  
258 =head2 option_spec
259  
260 Returns the L<Getopt::Long> specs of the check's options. None for base.
261  
262 =cut
263  
264 9 ▶sub option_spec { return () }
Subroutine option_spec: called CC=1 SCAR=0.0
Pod documented
265  
266 =head2 defaults
267  
268 Returns a hash ref of defaults for the check's options. None for base.
269  
270 =cut
271  
272 1696 ▶sub defaults { return {} }
Subroutine defaults: called CC=1 SCAR=0.0
Pod documented
273  
274 =head2 required
275  
276 Returns the options that must be given. None for base.
277  
278 =cut
279  
280 3166 ▶sub required { return () }
Subroutine required: called CC=1 SCAR=0.0
Pod documented
281  
282 =head2 ranges
283  
284 Returns the options that are ranges. None for base.
285  
286 =cut
287  
288 1552 ▶sub ranges { return () }
Subroutine ranges: called CC=1 SCAR=0.0
Pod documented
289  
290 =head2 validate
291  
292 Returns a list of what is wrong with the options, given as a hash ref.
293 Nothing for base.
294  
295 =cut
296  
297 1388 ▶sub validate { return () }
Subroutine validate: called CC=1 SCAR=0.0
Pod documented
298  
299 =head2 check
300  
301 Does the check. Dies for base, as each check has its own.
302  
303 =cut
304  
305 0 ▶sub check {
Subroutine check: not called CC=2 SCAR=17.9
Pod documented
306 0 ▶ die( ( ref( $_[0] ) || $_[0] ) . " has no check\n" );
Condition0%0/3
ref $_[0] || $_[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $_[0] || $_[0]
ref $_[0] $_[0]
Truth table0%0/3
A || B
A= ref $_[0]B= $_[0]
ABresult
1X1
011
000
307 }
308  
309 =head2 label
310  
311 Returns what starts the check's output, the upper cased name, such as
312 HTTP for Monitoring::Sneck::Checks::http.
313  
314 =cut
315  
316 3262 ▶sub label {
Subroutine label: called CC=2 SCAR=7.0
Pod documented
317 3262 ▶ my $label = ref( $_[0] ) || $_[0];
Condition66%2/3
ref $_[0] || $_[0]
l!l&&r!l&&!r
326020
MC/DC0%0/2
ref $_[0] || $_[0]
ref $_[0] $_[0]
Truth table66%2/3
A || B
A= ref $_[0]B= $_[0]
ABresult
1X1
011
000
318 3262 $label =~ s/\A.*:://;
319 3262 return uc($label);
320 }
321  
322 =head2 opt
323  
324 Returns the value of a option, or undef if it was not given and has no
325 default.
326  
327 my $host = $check->opt('hostname');
328  
329 =cut
330  
331 19381 ▶sub opt {
Subroutine opt: called CC=1 SCAR=0.0
Pod documented
332 19381 return $_[0]{options}{ $_[1] };
333 }
334  
335 =head2 timeout
336  
337 Returns the seconds to wait on the network, see L</COMMON OPTIONS>.
338  
339 =cut
340  
341 305 ▶sub timeout {
Subroutine timeout: called CC=3 SCAR=11.0
Pod documented
342 305 my ($self) = @_;
343  
344 305 ▶ return $self->{options}{timeout} + 0 if defined( $self->{options}{timeout} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"options"}{"timeout"} 10 295 305
345 295 my $timeout = $self->{run_timeout} - 1;
346  
347 295 ▶ return $timeout < 1 ? 1 : $timeout;
Branch: 1 branch
BranchTrueFalseTotal
$timeout < 1 ? : 1 294 295
348 }
349  
350 =head2 out
351  
352 Adds to the output.
353  
354 $check->out( "a line\n" );
355  
356 =cut
357  
358 2885 ▶sub out {
Subroutine out: called CC=1 SCAR=0.0
Pod documented
359 2885 my ( $self, @text ) = @_;
360  
361 2885 my $text = join( '', @text );
362 2885 $self->{stdout} = $self->{stdout} . $text;
363 2885 $self->{combined} = $self->{combined} . $text;
364  
365 2885 return;
366 }
367  
368 =head2 err
369  
370 Adds to the errors.
371  
372 $check->err( "could not read it\n" );
373  
374 =cut
375  
376 396 ▶sub err {
Subroutine err: called CC=1 SCAR=0.0
Pod documented
377 396 my ( $self, @text ) = @_;
378  
379 396 my $text = join( '', @text );
380 396 $self->{stderr} = $self->{stderr} . $text;
381 396 $self->{combined} = $self->{combined} . $text;
382  
383 396 return;
384 }
385  
386 =head2 finish
387  
388 Writes the status line and returns the code, so a check can end with
389 return $self->finish(...).
390  
391 - code :: OK, WARNING, CRITICAL, or UNKNOWN.
392  
393 - message :: What it found.
394  
395 - details :: Lines to add after the status line, the nagios long output.
396  
397 The line is the label, status, and message, with any perfdata after a |.
398  
399 return $self->finish( $self->OK, '200 OK in 0.120 seconds' );
400 # HTTP OK - 200 OK in 0.120 seconds | time=0.120s;1;2;0
401  
402 =cut
403  
404 2873 ▶sub finish {
Subroutine finish: called CC=2 SCAR=6.9
Pod documented
405 2873 my ( $self, $code, $message, @details ) = @_;
406  
407 2873 my $line = $self->label . ' ' . $self->status_name($code) . ' - ' . $message;
408 2873 ▶ if ( defined( $self->{perfdata}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"perfdata"}[0]) 1566 1307 2873
409 1566 $line = $line . ' | ' . join( ' ', @{ $self->{perfdata} } );
410 }
411 2873 $self->out( map { $_ . "\n" } ( $line, @details ) );
412  
413 2873 return $code;
414 } ## end sub finish
415  
416 =head2 status_name
417  
418 Returns the name of a code, such as CRITICAL for 2.
419  
420 =cut
421  
422 2874 ▶sub status_name {
Subroutine status_name: called CC=2 SCAR=7.6
Pod documented
423 2874 ▶ return $STATUS_NAMES[ $_[1] ] // 'UNKNOWN';
Condition50%1/2
$Monitoring::Sneck::Checks::base::STATUS_NAMES[$_[1]] // "UNKNOWN"
l!l
28740
MC/DC0%0/1
$Monitoring::Sneck::Checks::base::STATUS_NAMES[$_[1]] // "UNKNOWN"
$Monitoring::Sneck::Checks::base::STATUS_NAMES[$_[1]]
Truth table50%1/2
A
A= $Monitoring::Sneck::Checks::base::STATUS_NAMES[$_[1]]
Aresult
11
00
424 }
425  
426 =head2 worst
427  
428 Returns the worst of the codes given, CRITICAL, then WARNING, then
429 UNKNOWN, then OK. OK if none are given.
430  
431 my $code = $check->worst( $check->OK, $check->UNKNOWN, $check->WARNING );
432 # WARNING
433  
434 =cut
435  
436 2747 ▶sub worst {
Subroutine worst: called CC=3 SCAR=11.0
Pod documented
437 2747 my ( $self, @codes ) = @_;
438  
439 2747 my $worst = OK;
440 2747 foreach my $code (@codes) {
441 5814 ▶ $worst = $code if $SEVERITY{$code} > $SEVERITY{$worst};
Branch: 1 branch
BranchTrueFalseTotal
if $Monitoring::Sneck::Checks::base::SEVERITY{$code} > $Monitoring::Sneck::Checks::base::SEVERITY{$worst} 1608 4206 5814
442 }
443  
444 2747 return $worst;
445 } ## end sub worst
446  
447 =head2 parse_range
448  
449 Parses a range, see L</RANGES>. Dies if it is not valid.
450  
451 Returns a hash ref of start, undef for negative infinity, end, undef for
452 infinity, and inside, 1 if it starts with @.
453  
454 my $range = $check->parse_range('@10:20');
455 # { start => 10, end => 20, inside => 1 }
456  
457 =cut
458  
459 5554 ▶sub parse_range {
Subroutine parse_range: called CC=12 SCAR=25.0
Pod documented
460 5554 my ( $self, $text ) = @_;
461  
462 5554 ▶ die("is not a range\n") if !defined($text) || ref($text);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $text or ref $text 0 5554 5554
Condition33%1/3
not defined $text or ref $text
l!l&&r!l&&!r
005554
MC/DC0%0/2
not defined $text or ref $text
not defined $text ref $text
Truth table33%1/3
not(A) or B
A= not defined $textB= ref $text
ABresult
1X1
011
000
463 5554 my $spec = $text;
464 5554 ▶ my $inside = ( $spec =~ s/\A\@// ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$spec =~ s/\A\@//u ? : 25 5529 5554
465 5554 my ( $start, $end );
466 5554 ▶ if ( $spec =~ /\A($NUMBER)\z/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($spec =~ /\A($Monitoring::Sneck::Checks::base::NUMBER)\z/u) { } 5379 175 5554
elsif ($spec ne ':' and $spec =~ /\A(~|$Monitoring::Sneck::Checks::base::NUMBER)?:($Monitoring::Sneck::Checks::base::NUMBER)?\z/u) { } 163 12 175
467 5379 ( $start, $end ) = ( 0, $1 );
468 ▶ } elsif ( $spec ne ':' && $spec =~ /\A(~|$NUMBER)?:($NUMBER)?\z/ ) {
Condition100%3/3
$spec ne ":" and $spec =~ /\A(~|$Monitoring::Sneck::Checks::base::NUMBER)?:($Monitoring::Sneck::Checks::base::NUMBER)?\z/u
!ll&&!rl&&r
111163
MC/DC100%2/2
$spec ne ":" and $spec =~ /\A(~|$Monitoring::Sneck::Checks::base::NUMBER)?:($Monitoring::Sneck::Checks::base::NUMBER)?\z/u
$spec ne ":" $spec =~ /\A(~|$Monitoring::Sneck::Checks::base::NUMBER)?:($Monitoring::Sneck::Checks::base::NUMBER)?\z/u
Truth table100%3/3
A and B
A= $spec ne ":"B= $spec =~ /\A(~|$Monitoring::Sneck::Checks::base::NUMBER)?:($Monitoring::Sneck::Checks::base::NUMBER)?\z/u
ABresult
0X0
100
111
469 163 ▶ $start = $1 // 0;
Condition50%1/2
$1 // 0
l!l
1630
MC/DC0%0/1
$1 // 0
$1
Truth table50%1/2
A
A= $1
Aresult
11
00
470 163 $end = $2;
471 163 ▶ $start = undef if $start eq '~';
Branch: 1 branch
BranchTrueFalseTotal
if $start eq "~" 24 139 163
472 } else {
473 12 die( '"' . $text . '" is not a valid range' . "\n" );
474 }
475 5542 ▶ if ( defined($start) && defined($end) && $start > $end ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $start and defined $end and $start > $end) 1 5541 5542
Condition100%6/6
defined $start and defined $end and $start > $end
!ll&&!rl&&r
13454071
defined $start and defined $end
!ll&&!rl&&r
241105408
MC/DC100%3/3
defined $start and defined $end and $start > $end
defined $start defined $end $start > $end
Truth table100%4/4
A and B and C
A= defined $startB= defined $endC= $start > $end
ABCresult
0XX0
10X0
1100
1111
476 1 die( '"' . $text . '" starts after it ends' . "\n" );
477 }
478  
479 5541 return { start => $start, end => $end, inside => $inside };
480 } ## end sub parse_range
481  
482 =head2 in_alert
483  
484 Returns 1 if a value alerts for a range, else 0.
485  
486 $check->in_alert( 15, '10' ); # 1
487 $check->in_alert( 15, '10:' ); # 0
488  
489 =cut
490  
491 2243 ▶sub in_alert {
Subroutine in_alert: called CC=7 SCAR=19.5
Pod documented
492 2243 my ( $self, $value, $range ) = @_;
493  
494 2243 ▶ $range = $self->parse_range($range) if ref($range) ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $range ne "HASH" 2243 0 2243
495 my $within = ( !defined( $range->{start} ) || $value >= $range->{start} )
496 2243 ▶ && ( !defined( $range->{end} ) || $value <= $range->{end} );
Condition100%9/9
(!defined($range->{'start'}) || $value >= $range->{'start'}) && (!defined($range->{'end'}) || $value <= $range->{'end'})
!ll&&!rl&&r
115881644
not defined $range->{"start"} or $value >= $range->{"start"}
l!l&&r!l&&!r
12222011
not defined $range->{"end"} or $value <= $range->{"end"}
l!l&&r!l&&!r
471597588
MC/DC100%4/4
(!defined($range->{'start'}) || $value >= $range->{'start'}) && (!defined($range->{'end'}) || $value <= $range->{'end'})
not defined $range->{"start"} $value >= $range->{"start"} not defined $range->{"end"} $value <= $range->{"end"}
Truth table100%7/7
not(A) or B && not(C) or D
A= not defined $range->{"start"}B= $value >= $range->{"start"}C= not defined $range->{"end"}D= $value <= $range->{"end"}
ABCDresult
00XX0
1X000
01000
1X1X1
1X011
011X1
01011
497  
498 2243 ▶ return ( $within xor !$range->{inside} ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$within ^^ !$range->{'inside'} ? : 606 1637 2243
Condition100%4/4
$within xor not $range->{"inside"}
l&&rl&&!r!l&&r!l&&!r
1634105963
MC/DC100%2/2
$within xor not $range->{"inside"}
$within not $range->{"inside"}
Truth table100%4/4
A xor not(B)
A= $withinB= not $range->{"inside"}
ABresult
110
101
011
000
499 }
500  
501 =head2 threshold_status
502  
503 Returns CRITICAL if a value alerts for the critical range, WARNING if
504 for the warning one, else OK. A undef range is skipped.
505  
506 my $code = $check->threshold_status( $seconds, $check->opt('warning'), $check->opt('critical') );
507  
508 =cut
509  
510 2168 ▶sub threshold_status {
Subroutine threshold_status: called CC=5 SCAR=16.1
Pod documented
511 2168 my ( $self, $value, $warning, $critical ) = @_;
512  
513 2168 ▶ return CRITICAL if defined($critical) && $self->in_alert( $value, $critical );
Branch: 1 branch
BranchTrueFalseTotal
if defined $critical and $self->in_alert($value, $critical) 208 1960 2168
Condition100%3/3
defined $critical and $self->in_alert($value, $critical)
!ll&&!rl&&r
1239721208
MC/DC100%2/2
defined $critical and $self->in_alert($value, $critical)
defined $critical $self->in_alert($value, $critical)
Truth table100%3/3
A and B
A= defined $criticalB= $self->in_alert($value, $critical)
ABresult
0X0
100
111
514 1960 ▶ return WARNING if defined($warning) && $self->in_alert( $value, $warning );
Branch: 1 branch
BranchTrueFalseTotal
if defined $warning and $self->in_alert($value, $warning) 389 1571 1960
Condition100%3/3
defined $warning and $self->in_alert($value, $warning)
!ll&&!rl&&r
671900389
MC/DC100%2/2
defined $warning and $self->in_alert($value, $warning)
defined $warning $self->in_alert($value, $warning)
Truth table100%3/3
A and B
A= defined $warningB= $self->in_alert($value, $warning)
ABresult
0X0
100
111
515  
516 1571 return OK;
517 }
518  
519 =head2 perfdata
520  
521 Adds perfdata, which finish puts after the status line.
522  
523 - label :: The name, quoted if it needs it.
524  
525 - value :: The value.
526  
527 - uom :: The unit, such as s, B, or %.
528  
529 - warning, critical, min, max :: As in the nagios plugin guidelines.
530  
531 Returns the perfdata as text.
532  
533 $check->perfdata( label => 'time', value => '0.120', uom => 's', warning => 1, critical => 2, min => 0 );
534 # time=0.120s;1;2;0
535  
536 =cut
537  
538 3857 ▶sub perfdata {
Subroutine perfdata: called CC=4 SCAR=13.9
Pod documented
539 3857 my ( $self, %perf ) = @_;
540  
541 3857 my $label = $perf{label};
542 3857 ▶ if ( $label =~ /[\s'=]/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($label =~ /[\s'=]/u) 218 3639 3857
543 218 $label =~ s/'/''/g;
544 218 $label = "'" . $label . "'";
545 }
546 3857 ▶ my $text = $label . '=' . $perf{value} . ( $perf{uom} // '' );
Condition100%2/2
$perf{"uom"} // ""
l!l
13992458
MC/DC100%1/1
$perf{"uom"} // ""
$perf{"uom"}
Truth table100%2/2
A
A= $perf{"uom"}
Aresult
11
00
547 3857 ▶ $text = $text . ';' . join( ';', map { $_ // '' } @perf{ 'warning', 'critical', 'min', 'max' } );
Condition100%2/2
$_ // ""
l!l
74327996
MC/DC100%1/1
$_ // ""
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
548 3857 $text =~ s/;+\z//;
549 3857 push( @{ $self->{perfdata} }, $text );
550  
551 3857 return $text;
552 } ## end sub perfdata
553  
554 =head2 is_host
555  
556 Returns 1 if the text is a IP or hostname, else 0.
557  
558 $check->is_host('www.example.org'); # 1
559 $check->is_host('not a host'); # 0
560  
561 =cut
562  
563 198 ▶sub is_host {
Subroutine is_host: called CC=4 SCAR=13.9
Pod documented
564 198 my ( $self, $host ) = @_;
565  
566 198 require Data::Validate::IP;
567 198 require Data::Validate::Domain;
568 198 ▶ return 0 if !defined($host);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $host 0 198 198
569 198 ▶ return 1 if Data::Validate::IP::is_ip($host);
Branch: 1 branch
BranchTrueFalseTotal
if Data::Validate::IP::is_ip($host) 88 110 198
570 110 ▶ return 1 if Data::Validate::Domain::is_hostname($host);
Branch: 1 branch
BranchTrueFalseTotal
if Data::Validate::Domain::is_hostname($host) 105 5 110
571  
572 5 return 0;
573 } ## end sub is_host
574  
575 =head2 user_agent
576  
577 Returns a L<LWP::UserAgent> using the timeout, not following
578 redirects, and checking certificates.
579  
580 - insecure :: 1 to not check certificates.
581  
582 - ca_file :: The CA file to check them against.
583  
584 - max_redirect :: Redirects to follow.
585 Default :: 0
586  
587 my $user_agent = $check->user_agent( insecure => $check->opt('insecure') );
588  
589 =cut
590  
591 33 ▶sub user_agent {
Subroutine user_agent: called CC=5 SCAR=16.2
Pod documented
592 33 my ( $self, %opts ) = @_;
593  
594 33 require LWP::UserAgent;
595 33 ▶ my %ssl_opts = ( verify_hostname => $opts{insecure} ? 0 : 1 );
Branch: 1 branch
BranchTrueFalseTotal
$opts{'insecure'} ? : 1 32 33
596 33 ▶ $ssl_opts{SSL_verify_mode} = 0 if $opts{insecure};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"insecure"} 1 32 33
597 33 ▶ $ssl_opts{SSL_ca_file} = $opts{ca_file} if defined( $opts{ca_file} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"ca_file"} 0 33 33
598  
599 return LWP::UserAgent->new(
600 agent => 'Monitoring::Sneck::Checks/' . $VERSION,
601 timeout => $self->timeout,
602 33 ▶ max_redirect => $opts{max_redirect} // 0,
Condition50%1/2
$opts{"max_redirect"} // 0
l!l
330
MC/DC0%0/1
$opts{"max_redirect"} // 0
$opts{"max_redirect"}
Truth table50%1/2
A
A= $opts{"max_redirect"}
Aresult
11
00
603 keep_alive => 0,
604 ssl_opts => \%ssl_opts,
605 );
606 } ## end sub user_agent
607  
608 =head2 resolver
609  
610 Returns a L<Net::DNS::Resolver> using the timeout.
611  
612 - servers :: Array ref of the servers to ask. The system's if not
613 given.
614  
615 - tcp :: 1 to ask over TCP.
616  
617 - no_recurse :: 1 to not ask for recursion, for asking authoritative
618 servers.
619  
620 my $resolver = $check->resolver( servers => ['192.0.2.53'] );
621  
622 =cut
623  
624 60 ▶sub resolver {
Subroutine resolver: called CC=5 SCAR=16.2
Pod documented
625 60 my ( $self, %opts ) = @_;
626  
627 60 require Net::DNS;
628 my $resolver = Net::DNS::Resolver->new(
629 udp_timeout => $self->timeout,
630 tcp_timeout => $self->timeout,
631 retry => 2,
632 usevc => $opts{tcp} ? 1 : 0,
633 60 ▶ recurse => $opts{no_recurse} ? 0 : 1,
Branch: 2 branches
BranchTrueFalseTotal
$opts{'tcp'} ? : 0 60 60
$opts{'no_recurse'} ? : 24 36 60
634 );
635 60 ▶ if ( ref( $opts{servers} ) eq 'ARRAY' && defined( $opts{servers}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $opts{"servers"} eq "ARRAY" and defined $opts{"servers"}[0]) 44 16 60
Condition66%2/3
ref $opts{"servers"} eq "ARRAY" and defined $opts{"servers"}[0]
!ll&&!rl&&r
16044
MC/DC50%1/2
ref $opts{"servers"} eq "ARRAY" and defined $opts{"servers"}[0]
ref $opts{"servers"} eq "ARRAY" defined $opts{"servers"}[0]
Truth table66%2/3
A and B
A= ref $opts{"servers"} eq "ARRAY"B= defined $opts{"servers"}[0]
ABresult
0X0
100
111
636 44 $resolver->nameservers( @{ $opts{servers} } );
637 }
638  
639 60 return $resolver;
640 } ## end sub resolver
641  
642 =head2 cert_details
643  
644 Returns details on a certificate, a Net::SSLeay X509, as a hash ref.
645  
646 - subject :: The common name, or the whole subject if it has none.
647  
648 - issuer :: The same, for the issuer.
649  
650 - not_before, not_after :: When it is good from and to, as time since epoch.
651  
652 - days_left :: Whole days until not_after, negative once past it.
653  
654 - names :: Array ref of its subject alternative names, such as DNS:www.example.org.
655  
656 my $details = $check->cert_details( $socket->peer_certificate );
657  
658 =cut
659  
660 59 ▶sub cert_details {
Subroutine cert_details: called CC=2 SCAR=7.2
Pod documented
661 59 my ( $self, $cert ) = @_;
662  
663 59 require IO::Socket::SSL::Utils;
664 59 my $hash = IO::Socket::SSL::Utils::CERT_asHash($cert);
665 118 ▶ my $name = sub {
Subroutine __ANON__: called CC=2 SCAR=10.1
666 118 my ($fields) = @_;
667 118 ▶ return $fields->{commonName} if defined( $fields->{commonName} );
Branch: 1 branch
BranchTrueFalseTotal
if defined $fields->{"commonName"} 118 0 118
668 0 return join( ', ', map { $_ . '=' . $fields->{$_} } sort( keys( %{$fields} ) ) );
669 59 };
670  
671 return {
672 subject => $name->( $hash->{subject} ),
673 issuer => $name->( $hash->{issuer} ),
674 not_before => $hash->{not_before},
675 not_after => $hash->{not_after},
676 days_left => POSIX::floor( ( $hash->{not_after} - time ) / 86400 ),
677 59 ▶ names => [ map { $_->[0] . ':' . $_->[1] } @{ $hash->{subjectAltNames} // [] } ],
Condition100%2/2
$hash->{"subjectAltNames"} // []
l!l
4118
MC/DC100%1/1
$hash->{"subjectAltNames"} // []
$hash->{"subjectAltNames"}
Truth table100%2/2
A
A= $hash->{"subjectAltNames"}
Aresult
11
00
678 };
679 } ## end sub cert_details
680  
681 =head2 cert_status
682  
683 Works out the status of a certificate from when it is good to.
684  
685 - details :: From L</cert_details>.
686  
687 - warning :: Days left at or under which it is WARNING.
688  
689 - critical :: Days left at or under which it is CRITICAL.
690  
691 Returns the code and a message. Expired or not good yet is CRITICAL.
692  
693 my ( $code, $message ) = $check->cert_status( $details, 30, 14 );
694 # ( 1, '"www.example.org" expires in 20 days, 2026-11-21 12:00:00 UTC' )
695  
696 =cut
697  
698 60 ▶sub cert_status {
Subroutine cert_status: called CC=8 SCAR=20.9
Pod documented
699 60 my ( $self, $details, $warning, $critical ) = @_;
700  
701 60 my $now = time;
702 60 my $name = '"' . $details->{subject} . '"';
703 60 ▶ if ( $details->{not_before} > $now ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($details->{"not_before"} > $now) 1 59 60
704 1 return ( CRITICAL, $name . ' is not good until ' . $self->utc_time( $details->{not_before} ) );
705 }
706 59 ▶ if ( $details->{not_after} <= $now ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($details->{"not_after"} <= $now) 1 58 59
707 1 return ( CRITICAL, $name . ' expired ' . $self->utc_time( $details->{not_after} ) );
708 }
709  
710 58 my $days_left = POSIX::floor( ( $details->{not_after} - $now ) / 86400 );
711 my $message
712 = $name
713 . ' expires in '
714 . $days_left . ' day'
715 . ( $days_left == 1 ? '' : 's' ) . ', '
716 58 ▶ . $self->utc_time( $details->{not_after} );
Branch: 1 branch
BranchTrueFalseTotal
$days_left == 1 ? : 0 58 58
717 58 ▶ return ( CRITICAL, $message ) if defined($critical) && $days_left <= $critical;
Branch: 1 branch
BranchTrueFalseTotal
if defined $critical and $days_left <= $critical 4 54 58
Condition66%2/3
defined $critical and $days_left <= $critical
!ll&&!rl&&r
0544
MC/DC50%1/2
defined $critical and $days_left <= $critical
defined $critical $days_left <= $critical
Truth table66%2/3
A and B
A= defined $criticalB= $days_left <= $critical
ABresult
0X0
100
111
718 54 ▶ return ( WARNING, $message ) if defined($warning) && $days_left <= $warning;
Branch: 1 branch
BranchTrueFalseTotal
if defined $warning and $days_left <= $warning 8 46 54
Condition66%2/3
defined $warning and $days_left <= $warning
!ll&&!rl&&r
0468
MC/DC50%1/2
defined $warning and $days_left <= $warning
defined $warning $days_left <= $warning
Truth table66%2/3
A and B
A= defined $warningB= $days_left <= $warning
ABresult
0X0
100
111
719  
720 46 return ( OK, $message );
721 } ## end sub cert_status
722  
723 =head2 utc_time
724  
725 Returns a time since epoch as text, such as 2026-11-21 12:00:00 UTC.
726  
727 =cut
728  
729 60 ▶sub utc_time {
Subroutine utc_time: called CC=1 SCAR=0.0
Pod documented
730 60 return POSIX::strftime( '%Y-%m-%d %H:%M:%S UTC', gmtime( $_[1] ) );
731 }
732  
733 =head2 read_socket
734  
735 Reads from a socket until done says so, it closes, or the timeout
736 passes.
737  
738 - socket :: The socket, plain or TLS.
739  
740 - done :: A code ref given what has been read so far, returning true
741 once it is enough.
742  
743 Returns what was read.
744  
745 my $greeting = $check->read_socket( $socket, sub { $_[0] =~ /^\d{3} [^\n]*\n/m } );
746  
747 =cut
748  
749 44 ▶sub read_socket {
Subroutine read_socket: called CC=7 SCAR=19.5
Pod documented
750 44 my ( $self, $socket, $done ) = @_;
751  
752 44 my $received = '';
753 44 my $select = IO::Select->new($socket);
754 44 my $deadline = Time::HiRes::time + $self->timeout;
755 44 while (1) {
756 45 my $remaining = $deadline - Time::HiRes::time;
757 45 ▶ last if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 0 45 45
758  
759 # TLS may already have data read in that select can not see
760 45 ▶ my $pending = $socket->can('pending') ? $socket->pending : 0;
Branch: 1 branch
BranchTrueFalseTotal
$socket->can('pending') ? : 7 38 45
761 45 ▶ last if !$pending && !$select->can_read($remaining);
Branch: 1 branch
BranchTrueFalseTotal
unless $pending or $select->can_read($remaining) 1 44 45
Condition66%2/3
$pending or $select->can_read($remaining)
l!l&&r!l&&!r
0441
MC/DC50%1/2
$pending or $select->can_read($remaining)
$pending $select->can_read($remaining)
Truth table66%2/3
A or B
A= $pendingB= $select->can_read($remaining)
ABresult
1X1
011
000
762 44 my $read = sysread( $socket, my $buffer, 4096 );
763 44 ▶ last if !$read;
Branch: 1 branch
BranchTrueFalseTotal
unless $read 3 41 44
764 41 $received = $received . $buffer;
765 41 ▶ last if $done->($received);
Branch: 1 branch
BranchTrueFalseTotal
if &$done($received) 40 1 41
766 } ## end while (1)
767  
768 44 return $received;
769 } ## end sub read_socket
770  
771 =head2 pem_certs
772  
773 Reads the certificates in a PEM file. Dies if it can not be read.
774  
775 Returns a array ref of a Net::SSLeay X509 for each, in order, undef
776 for any that can not be parsed. Empty if there are none. Free them
777 with L<IO::Socket::SSL::Utils/CERT_free>.
778  
779 my $certs = $check->pem_certs('/usr/local/etc/ssl/www-chain.pem');
780  
781 =cut
782  
783 41 ▶sub pem_certs {
Subroutine pem_certs: called CC=4 SCAR=13.9
Pod documented
784 41 my ( $self, $file ) = @_;
785  
786 41 require IO::Socket::SSL::Utils;
787 41 my $content = read_file( $file, err_mode => 'quiet' );
788 41 ▶ die( 'can not read ' . $file . ', ' . $! . "\n" ) if !defined($content);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 1 40 41
789  
790 40 my @certs;
791 40 foreach my $pem ( $content =~ /(-----BEGIN CERTIFICATE-----.+?-----END CERTIFICATE-----)/gs ) {
792 48 my $cert = eval { IO::Socket::SSL::Utils::PEM_string2cert($pem) };
793 48 ▶ push( @certs, $cert ? $cert : undef );
Branch: 1 branch
BranchTrueFalseTotal
$cert ? : 46 2 48
794 }
795  
796 40 return \@certs;
797 } ## end sub pem_certs
798  
799 =head2 run_command
800  
801 Runs a command, without a shell, and waits for it, with stdin from
802 /dev/null. Dies if it can not be run.
803  
804 - command :: The program and its args, as a list.
805  
806 Returns its exit code and its stdout and stderr together. A command
807 killed by a signal has a exit of 128 plus the signal.
808  
809 If the check times out while the command runs, the command, and
810 anything it started, is sent TERM, then KILL if it is still there half
811 a second later, so a hung command does not hold the check up past its
812 timeout. For that it is run in a process group of its own.
813  
814 my ( $exit, $output ) = $check->run_command( '/usr/sbin/pkg', 'audit' );
815  
816 =cut
817  
818 2577 ▶sub run_command {
Subroutine run_command: called CC=9 SCAR=22.4
Pod documented
819 2577 my ( $self, @command ) = @_;
820  
821 # a forking pipe open sets up the child's fd 1 itself, which matters as run has STDOUT
822 # pointed at a in-memory handle, so the rest is done on fds as well
823 2577 ▶ my $pid = open( my $out, '-|' ) // die( 'can not fork for ' . $command[0] . ', ' . $! . "\n" );
Condition50%1/2
open(my $out, "-|") // die('can not fork for ' . $command[0] . ', ' . $! . "\n")
l!l
25770
MC/DC0%0/1
open(my $out, "-|") // die('can not fork for ' . $command[0] . ', ' . $! . "\n")
open(my $out, "-|")
Truth table50%1/2
A
A= open(my $out, "-|")
Aresult
11
00
824 2577 ▶ if ( !$pid ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($pid) 239 2338 2577
825 # its own process group, so _stop_command can take anything it starts down with it
826 239 POSIX::setpgid( 0, 0 );
827 239 POSIX::dup2( 1, 2 );
828 239 my $null = POSIX::open( '/dev/null', POSIX::O_RDONLY() );
829 239 ▶ POSIX::dup2( $null, 0 ) if defined($null);
Branch: 1 branch
BranchTrueFalseTotal
if defined $null 239 0 239
830 292 ▶ { no warnings 'exec'; exec( { $command[0] } @command ); }
Subroutine BEGIN: called CC=1 SCAR=0.0
831 0 my $why = "\0" . 'can not run ' . $command[0] . ', ' . $!;
832 0 POSIX::write( 1, $why, length($why) );
833 0 POSIX::_exit(127);
834 } ## end if ( !$pid )
835  
836 # the timeout alarm dies out of the read, and closing the pipe waits for the command,
837 # so a hung one is stopped first or the close would wait as long as it does
838 2338 my $output = eval { local $/; <$out> };
839 2338 ▶ if ( $@ ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ ne "") 10 2328 2338
840 10 my $died = $@;
841 10 _stop_command($pid);
842 10 close($out);
843 10 die($died);
844 }
845 2328 ▶ $output //= '';
Condition50%1/2
$output //= ""
l!l
23280
MC/DC0%0/1
$output //= ""
$output
Truth table50%1/2
A
A= $output
Aresult
11
00
846 2328 close($out);
847 2328 ▶ my $exit = ( $? & 127 ) ? 128 + ( $? & 127 ) : $? >> 8;
Branch: 1 branch
BranchTrueFalseTotal
$? & 127 ? : 0 2328 2328
848 2328 ▶ die( substr( $output, 1 ) . "\n" ) if $exit == 127 && $output =~ /\A\0can not run /;
Branch: 1 branch
BranchTrueFalseTotal
if $exit == 127 and $output =~ /\A\0can not run /u 11 2317 2328
Condition66%2/3
$exit == 127 and $output =~ /\A\0can not run /u
!ll&&!rl&&r
2317011
MC/DC50%1/2
$exit == 127 and $output =~ /\A\0can not run /u
$exit == 127 $output =~ /\A\0can not run /u
Truth table66%2/3
A and B
A= $exit == 127B= $output =~ /\A\0can not run /u
ABresult
0X0
100
111
849  
850 2317 return ( $exit, $output );
851 } ## end sub run_command
852  
853 # Stops a command run_command started, once the check timed out while
854 # waiting on it. TERM first, then KILL if it has not gone after half a
855 # second, so closing the pipe to it, which waits for it, can not hang.
856 # Both go to its process group as well as to it, as the group takes
857 # anything it started with it, and it may not have made the group yet.
858 #
859 # Args...
860 #
861 # - pid :: The process ID of the command.
862 #
863 # Returns nothing. A command that exits on TERM is reaped here, which
864 # the close after it copes with.
865 #
866 # Example...
867 #
868 # _stop_command($pid);
869 10 ▶sub _stop_command {
Subroutine _stop_command: called CC=3 SCAR=11.6
870 10 my ($pid) = @_;
871  
872 10 kill( 'TERM', $pid );
873 10 kill( '-TERM', $pid );
874 10 foreach ( 1 .. 10 ) {
875 20 ▶ return if waitpid( $pid, POSIX::WNOHANG() ) != 0;
Branch: 1 branch
BranchTrueFalseTotal
if waitpid($pid, 1) != 0 10 10 20
876 10 Time::HiRes::sleep(0.05);
877 }
878 0 kill( 'KILL', $pid );
879 0 kill( '-KILL', $pid );
880  
881 0 return;
882 } ## end sub _stop_command
883  
884 =head2 split_expect
885  
886 Splits a expect, a name, a comparison, and a value, as sysctl and
887 config_value take. The comparison is =, !=, <, <=, >, or >=.
888  
889 Returns the name, comparison, and value, or a empty list if it is not
890 valid.
891  
892 my ( $name, $comparison, $value ) = $check->split_expect('kern.securelevel>=1');
893 # ( 'kern.securelevel', '>=', '1' )
894  
895 =cut
896  
897 182 ▶sub split_expect {
Subroutine split_expect: called CC=2 SCAR=6.9
Pod documented
898 182 my ( $self, $expect ) = @_;
899  
900 182 ▶ return ( $1, $2, $3 ) if $expect =~ m{\A([A-Za-z0-9_][A-Za-z0-9_./-]*?)(!=|<=|>=|=|<|>)(.*)\z};
Branch: 1 branch
BranchTrueFalseTotal
if $expect =~ m[\A([A-Za-z0-9_][A-Za-z0-9_./-]*?)(!=|<=|>=|=|<|>)(.*)\z]u 176 6 182
901  
902 6 return ();
903 }
904  
905 =head2 expect_met
906  
907 Checks a value against a expect.
908  
909 - value :: The value it has.
910  
911 - comparison :: =, !=, <, <=, >, or >=.
912  
913 - wanted :: The value wanted. For = and !=, values split by |, any of
914 which is enough for =, and none of which may match for !=. Runs of
915 space in them are squashed. A empty one, as all of "name=" or the last
916 of "name=a|", is met by a empty value. The others compare as numbers,
917 and a value that is not a number does not meet them.
918  
919 - no_case :: 1 to compare = and != without case.
920  
921 Returns 1 if it is met, else 0.
922  
923 $check->expect_met( '1', '=', '1|2' ); # 1
924 $check->expect_met( '5', '<', '3' ); # 0
925 $check->expect_met( '', '=', '' ); # 1
926  
927 =cut
928  
929 67 ▶sub expect_met {
Subroutine expect_met: called CC=15 SCAR=27.8
Pod documented
930 67 my ( $self, $value, $comparison, $wanted, $no_case ) = @_;
931  
932 67 ▶ if ( $comparison eq '=' || $comparison eq '!=' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($comparison eq "=" or $comparison eq "!=") 54 13 67
Condition100%3/3
$comparison eq "=" or $comparison eq "!="
l!l&&r!l&&!r
47713
MC/DC100%2/2
$comparison eq "=" or $comparison eq "!="
$comparison eq "=" $comparison eq "!="
Truth table100%3/3
A or B
A= $comparison eq "="B= $comparison eq "!="
ABresult
1X1
011
000
933 54 ▶ my $have = $no_case ? lc($value) : $value;
Branch: 1 branch
BranchTrueFalseTotal
$no_case ? : 13 41 54
934 54 ▶ my $found = grep { ( $no_case ? lc($_) : $_ ) eq $have } map { s/\s+/ /gr } _split_wanted($wanted);
Branch: 1 branch
BranchTrueFalseTotal
$no_case ? : 17 46 63
935 54 ▶ return ( $comparison eq '=' ? $found : !$found ) ? 1 : 0;
Branch: 2 branches
BranchTrueFalseTotal
($comparison eq '=' ? $found : !$found) ? : 33 21 54
$comparison eq '=' ? : 47 7 54
936 }
937 13 ▶ return 0 if $value !~ /\A-?[0-9]+(?:\.[0-9]+)?\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $value =~ /\A-?[0-9]+(?:\.[0-9]+)?\z/u 0 13 13
938 13 ▶ return ( $value < $wanted ? 1 : 0 ) if $comparison eq '<';
Branch: 2 branches
BranchTrueFalseTotal
if $comparison eq "<" 0 13 13
$value < $wanted ? : 0 0 0
939 13 ▶ return ( $value <= $wanted ? 1 : 0 ) if $comparison eq '<=';
Branch: 2 branches
BranchTrueFalseTotal
if $comparison eq "<=" 2 11 13
$value <= $wanted ? : 1 1 2
940 11 ▶ return ( $value > $wanted ? 1 : 0 ) if $comparison eq '>';
Branch: 2 branches
BranchTrueFalseTotal
if $comparison eq ">" 0 11 11
$value > $wanted ? : 0 0 0
941  
942 11 ▶ return $value >= $wanted ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$value >= $wanted ? : 1 10 11
943 } ## end sub expect_met
944  
945 =head2 expect_wanted
946  
947 Returns what a expect wants as text, for messages, a empty value shown
948 as "".
949  
950 $check->expect_wanted( '>=', '1' ); # 'at least 1'
951 $check->expect_wanted( '=', 'a|b' ); # 'a or b'
952 $check->expect_wanted( '=', '' ); # '""'
953  
954 =cut
955  
956 32 ▶sub expect_wanted {
Subroutine expect_wanted: called CC=1 SCAR=0.0
Pod documented
957 32 my ( $self, $comparison, $wanted ) = @_;
958  
959 32 return $EXPECT_WORDS{$comparison} . join( ' or ', map { $self->shown($_) } _split_wanted($wanted) );
960 }
961  
962 =head2 shown
963  
964 Returns a value as it is to be shown in messages, which is as it is,
965 other than a empty one being "".
966  
967 $check->shown('022'); # '022'
968 $check->shown(''); # '""'
969  
970 =cut
971  
972 131 ▶sub shown {
Subroutine shown: called CC=2 SCAR=6.9
Pod documented
973 131 ▶ return $_[1] eq '' ? '""' : $_[1];
Branch: 1 branch
BranchTrueFalseTotal
$_[1] eq '' ? : 21 110 131
974 }
975  
976 # Splits what a expect wants on |, keeping empty ones, which split on
977 # its own drops, as name= and name=a| want a empty value.
978 #
979 # Args...
980 #
981 # - wanted :: The value wanted, such as 'a|b', 'a|', or ''.
982 #
983 # Returns the list of values, at least one.
984 #
985 # Example...
986 #
987 # _split_wanted('a|b'); # ( 'a', 'b' )
988 # _split_wanted('a|'); # ( 'a', '' )
989 # _split_wanted(''); # ( '' )
990 86 ▶sub _split_wanted {
Subroutine _split_wanted: called CC=2 SCAR=6.9
991 86 my ($wanted) = @_;
992  
993 86 ▶ return $wanted eq '' ? ('') : split( /\|/, $wanted, -1 );
Branch: 1 branch
BranchTrueFalseTotal
$wanted eq '' ? : 10 76 86
994 }
995  
996 =head2 read_state
997  
998 Reads state kept between runs, as JSON.
999  
1000 - file :: The state file.
1001  
1002 Returns a hash ref of it, a empty one if there is none yet, or undef
1003 if it can not be read or is not a JSON object.
1004  
1005 my $state = $check->read_state( $Monitoring::Sneck::Checks::base::STATE_DIR . '/interface-em0.json' );
1006  
1007 =cut
1008  
1009 290 ▶sub read_state {
Subroutine read_state: called CC=4 SCAR=13.9
Pod documented
1010 290 my ( $self, $file ) = @_;
1011  
1012 290 ▶ return {} if !-e $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $file 83 207 290
1013 207 require JSON;
1014 207 my $saved = read_file( $file, err_mode => 'quiet' );
1015 207 ▶ my $state = eval { JSON->new->decode( $saved // '' ) };
Condition50%1/2
$saved // ""
l!l
2070
MC/DC0%0/1
$saved // ""
$saved
Truth table50%1/2
A
A= $saved
Aresult
11
00
1016  
1017 207 ▶ return ref($state) eq 'HASH' ? $state : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $state eq 'HASH' ? : 206 1 207
1018 } ## end sub read_state
1019  
1020 =head2 write_state
1021  
1022 Writes the state, through a temporary file renamed into place, making
1023 the directory if needed.
1024  
1025 - file :: The state file.
1026  
1027 - state :: Hash ref of the state.
1028  
1029 Returns undef, or what went wrong.
1030  
1031 =cut
1032  
1033 288 ▶sub write_state {
Subroutine write_state: called CC=4 SCAR=15.0
Pod documented
1034 288 my ( $self, $file, $state ) = @_;
1035  
1036 288 require File::Basename;
1037 288 require JSON;
1038 288 my $dir = File::Basename::dirname($file);
1039 288 ▶ if ( !-d $dir && !mkdir( $dir, 0700 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-d $dir or mkdir $dir, 448) 0 288 288
Condition66%2/3
-d $dir or mkdir $dir, 448
l!l&&r!l&&!r
241470
MC/DC0%0/2
-d $dir or mkdir $dir, 448
-d $dir mkdir $dir, 448
Truth table66%2/3
A or B
A= -d $dirB= mkdir $dir, 448
ABresult
1X1
011
000
1040 0 return 'can not make ' . $dir . ', ' . $!;
1041 }
1042 288 ▶ if ( !write_file( $file, { err_mode => 'quiet', atomic => 1 }, JSON->new->canonical->encode($state) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (write_file($file, {"err_mode", "quiet", "atomic", 1}, "JSON"->new->canonical->encode($state))) 0 288 288
1043 0 return 'can not write ' . $file . ', ' . $!;
1044 }
1045  
1046 288 return undef;
1047 } ## end sub write_state
1048  
1049 =head2 os
1050  
1051 Returns the OS, as in $^O, such as linux or freebsd.
1052  
1053 =cut
1054  
1055 3535 ▶sub os {
Subroutine os: called CC=1 SCAR=0.0
Pod documented
1056 3535 return $OS;
1057 }
1058  
1059 =head2 sysctl
1060  
1061 Returns the value of a sysctl, through L<BSD::Sysctl>, which is only
1062 loaded when this is used, so only needed on the BSDs. Dies if it is not
1063 there.
1064  
1065 my $cpus = $check->sysctl('hw.ncpu');
1066  
1067 =cut
1068  
1069 122 ▶sub sysctl {
Subroutine sysctl: called CC=2 SCAR=6.9
Pod documented
1070 122 my ( $self, $name ) = @_;
1071  
1072 122 require BSD::Sysctl;
1073 122 my $value = BSD::Sysctl::sysctl($name);
1074 122 ▶ die( 'no sysctl ' . $name . "\n" ) if !defined($value);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 9 113 122
1075  
1076 113 return $value;
1077 }
1078  
1079 =head2 proc_file
1080  
1081 Returns the content of a file under Linux's /proc, such as meminfo.
1082 Dies if it can not be read.
1083  
1084 my $meminfo = $check->proc_file('meminfo');
1085  
1086 =cut
1087  
1088 1159 ▶sub proc_file {
Subroutine proc_file: called CC=2 SCAR=6.9
Pod documented
1089 1159 my ( $self, $file ) = @_;
1090  
1091 1159 my $content = read_file( $PROC . '/' . $file, err_mode => 'quiet' );
1092 1159 ▶ die( 'can not read ' . $PROC . '/' . $file . ', ' . $! . "\n" ) if !defined($content);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 86 1073 1159
1093  
1094 1073 return $content;
1095 }
1096  
1097 292 1;
« blib/lib/Monitoring/Sneck/Checks/service.pm ↑ Summary blib/lib/Monitoring/Sneck/Checks.pm »