blib/lib/Monitoring/Sneck.pm

filter: Statementstmt 96.6% 583 / 603 Branchbran 93.7% 253 / 270 Conditioncond 78.5% 117 / 149 MC/DCmcdc 71.0% 54 / 76 Subroutinesub 100% 31 / 31 Podpod 100% 2 / 2 totaltotal 91.9% 1040 / 1131 CC 215 SCAR 29.8
CC
215
Cov
93%
_read_compliance_state
45.9
_handle_restarts
33.0
_run_command
23.1
CRAP 19.6
↑ Summary blib/lib/Monitoring/Sneck/Config.pm »
1 package Monitoring::Sneck;
2  
3 59 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 59 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 59 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 59 ▶use Sys::Hostname qw(hostname);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 59 ▶use IPC::Open3 qw(open3);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 59 ▶use Symbol qw(gensym);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 59 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 59 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 59 ▶use POSIX qw(WNOHANG);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 59 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 59 ▶use File::Slurp qw(read_file write_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 59 ▶use Monitoring::Sneck::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 =head1 NAME
17  
18 Monitoring::Sneck - a boopable LibreNMS JSON style SNMP extend for remotely running nagios style checks
19  
20 =head1 VERSION
21  
22 Version 1.7.0
23  
24 =cut
25  
26 59 our $VERSION = '1.7.0';
27  
28 =head1 SYNOPSIS
29  
30 use Monitoring::Sneck;
31  
32 my $file='/usr/local/etc/sneck.conf';
33  
34 my $sneck=Monitoring::Sneck->new({config=>$file});
35  
36 =head1 DESCRIPTION
37  
38 This is not really meant to be used as a library. It exists to
39 support the sneck script.
40  
41 =head1 CONFIG FORMAT
42  
43 See L<Monitoring::Sneck::Config> for the config format and a example.
44  
45 =head1 USAGE
46  
47 snmpd just needs to print the cache. The simplest way is to cat the
48 GZip+BASE64 compressed cache, which avoids starting perl at all.
49  
50 extend sneck /bin/cat /var/cache/sneck.cache.snmp
51  
52 sneck -c may be used instead. It reports a missing cache file as error
53 JSON instead of printing nothing, but has to start perl and read the
54 config on each poll.
55  
56 extend sneck /usr/bin/env PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin /usr/local/bin/sneck -c
57  
58 If the cache file is changed via cache_file or B<-C>, cat its .snmp file
59 instead, or give B<-c> the same B<-C>.
60  
61 Then just setup a entry in like cron such as below.
62  
63 */5 * * * * /usr/bin/env PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin /usr/local/bin/sneck -u 2> /dev/null > /dev/null
64  
65 Most likely want to run it once per polling interval.
66  
67 You can use it in a non-cached manner with out cron, but this will result in a
68 longer polling time for LibreNMS or the like when it queries it.
69  
70 =head1 RETURN HASH
71  
72 The data section of the return hash is as below.
73  
74 - $hash{data}{alert} :: 0/1 boolean for if there is a alert or not.
75  
76 - $hash{data}{ok} :: Count of the number of ok checks.
77  
78 - $hash{data}{warning} :: Count of the number of warning checks.
79  
80 - $hash{data}{critical} :: Count of the number of critical checks.
81  
82 - $hash{data}{unknown} :: Count of the number of unknown checks.
83  
84 - $hash{data}{errored} :: Count of the number of errored checks.
85  
86 - $hash{data}{alertString} :: The cumulative outputs of anything
87 that returned a warning, critical, or unknown.
88  
89 - $hash{data}{vars} :: A hash with the variables to use.
90  
91 - $hash{data}{time} :: Time since epoch.
92  
93 - $hash{data}{hostname} :: The hostname the check was ran on.
94  
95 - $hash{data}{config} :: The raw config file if told to include it.
96  
97 - $hash{data}{run_time} :: How long it took to run all checks.
98  
99 - $hash{data}{restarted} :: Count of the number of restarts ran.
100  
101 - $hash{data}{restart_state_error} :: Only present if the restart
102 state file could not be read or written. Restarts still run if it
103 can't be read, as if there was no state.
104  
105 - $hash{data}{compliance_ok} :: Count of ok compliance checks.
106  
107 - $hash{data}{compliance_warning} :: Count of warning compliance
108 checks.
109  
110 - $hash{data}{compliance_critical} :: Count of critical compliance
111 checks.
112  
113 - $hash{data}{compliance_unknown} :: Count of unknown compliance
114 checks.
115  
116 - $hash{data}{compliance_errored} :: Count of errored compliance
117 checks.
118  
119 - $hash{data}{compliance_waived} :: Count of compliance checks that
120 were not ok but are waived. These are not counted anywhere else.
121  
122 - $hash{data}{compliance_alert} :: 0/1 for if any compliance check
123 is not ok and not waived. Only sets alert as well if the
124 compliance_alert option is set.
125  
126 - $hash{data}{compliance_alertString} :: The outputs of compliance
127 checks that are warning, critical, or unknown and not waived. Each
128 is prefixed with the control, or the name if there is none, and
129 the severity, such as '[CIS-5.2.10 high] '. Added to alertString
130 if the compliance_alert option is set.
131  
132 - $hash{data}{compliance_score} :: Percent of compliance checks that
133 are ok, leaving out waived ones, to two decimal places. undef if
134 there are none to score.
135  
136 - $hash{data}{compliance_frameworks}{$framework} :: The same counts
137 as above for compliance checks with that framework, as ok,
138 warning, critical, unknown, errored, waived, and score.
139  
140 - $hash{data}{compliance_state_error} :: Only present if the
141 compliance state file could not be read or written. Compliance
142 checks are run as if there was no state.
143  
144 For below '$name' is the name of the check in question.
145  
146 - $hash{data}{checks}{$name} :: A hash with info on the checks ran.
147  
148 - $hash{data}{checks}{$name}{check} :: The command pre-variable substitution.
149  
150 - $hash{data}{checks}{$name}{ran} :: The command ran.
151  
152 - $hash{data}{checks}{$name}{output} :: The output of the check.
153  
154 - $hash{data}{checks}{$name}{exit} :: The exit code. If it died on a
155 signal, this is 128 plus the signal number. If it could not be
156 executed or timed out, this is -1. For a perl check, -1 is it
157 not being able to be loaded and timing out is 3, see PERL CHECKS
158 in L<Monitoring::Sneck::Config>.
159  
160 - $hash{data}{checks}{$name}{error} :: Only present if it died on a
161 signal, timed out, or could not be executed. Provides a brief
162 description.
163  
164 - $hash{data}{checks}{$name}{run_time} :: How long it took to run the checks.
165  
166 - $hash{data}{checks}{$name}{rechecked_by} :: Only present if it was
167 rerun after a restart with check_restart set. The name of that
168 restart. The rest of the results are from the rerun.
169  
170 For below '$name' is the name of the debug checks in question. Debug
171 checks are run the same as checks, including check_timeout,
172 check_timeout_signal, and check_kill_sub_pids.
173  
174 - $hash{data}{debugs}{$name} :: A hash with info on the checks ran.
175  
176 - $hash{data}{debugs}{$name}{check} :: The command pre-variable substitution.
177  
178 - $hash{data}{debugs}{$name}{ran} :: The command ran.
179  
180 - $hash{data}{debugs}{$name}{output} :: The output of the check.
181  
182 - $hash{data}{debugs}{$name}{exit} :: The exit code. Same as for checks.
183  
184 - $hash{data}{debugs}{$name}{error} :: Only present if it died on a
185 signal, timed out, or could not be executed. Provides a brief
186 description.
187  
188 - $hash{data}{debugs}{$name}{run_time} :: How long it took to run the debug.
189  
190 For below '$name' is the name of the compliance check in question. They
191 are run the same as checks, except timeout may override check_timeout.
192 See COMPLIANCE in L<Monitoring::Sneck::Config>.
193  
194 - $hash{data}{compliance}{$name}{check}, ran, output, exit, error,
195 run_time :: The same as for checks. For a cached result, these are
196 from when it last ran.
197  
198 - $hash{data}{compliance}{$name}{last_ran} :: Time since epoch of
199 when it last started running.
200  
201 - $hash{data}{compliance}{$name}{cached} :: 0/1 for if this is a
202 earlier result reused because of interval.
203  
204 - $hash{data}{compliance}{$name}{waived} :: 0/1 for if it is not ok
205 and counted as waived. Errored is never waived.
206  
207 - $hash{data}{compliance}{$name}{control}, framework, severity,
208 waived_until, waiver :: Only present if set in the config.
209  
210 For below '$name' is the name of the restart in question. Every restart
211 in the config has a entry, even when restarts are disabled.
212  
213 - $hash{data}{restarts}{$name}{triggered} :: 0/1 for if enough of its
214 checks failed to meet its threshold.
215  
216 - $hash{data}{restarts}{$name}{ran} :: 0/1 for if it ran.
217  
218 - $hash{data}{restarts}{$name}{reason} :: Why it did or did not run.
219 One of 'threshold', 'cascade from $depend', 'cooldown, $N seconds
220 left', 'max retries reached', 'skipped, dependency $depend failed',
221 'maintenance window', 'not triggered', or 'restarts disabled'.
222  
223 - $hash{data}{restarts}{$name}{failed_checks} :: Array of the watched
224 checks that counted as failed.
225  
226 - $hash{data}{restarts}{$name}{threshold} :: The threshold.
227  
228 - $hash{data}{restarts}{$name}{attempts} :: Runs for its threshold
229 since its checks last recovered.
230  
231 - $hash{data}{restarts}{$name}{command} :: The command pre-variable
232 substitution.
233  
234 The rest are only present if it ran.
235  
236 - $hash{data}{restarts}{$name}{ran_command} :: The command ran.
237  
238 - $hash{data}{restarts}{$name}{output} :: The output of the command.
239  
240 - $hash{data}{restarts}{$name}{exit} :: The exit code. Same as for
241 checks.
242  
243 - $hash{data}{restarts}{$name}{error} :: Only present if it timed
244 out, died on a signal, or could not be executed. If it timed out
245 and timeout_signal is set, also says the signal was sent, plus
246 any problems sending it. Also present if check_restart is set and its
247 checks still met the threshold afterwards, unless one of the
248 above already set it.
249  
250 - $hash{data}{restarts}{$name}{run_time} :: How long the command
251 took to run, not counting check_restart.
252  
253 - $hash{data}{restarts}{$name}{recheck_failed_checks} :: Only present
254 if check_restart is set. Array of the watched checks that still
255 counted as failed when rerun.
256  
257 A restart that ran and failed, including timing out or its checks still
258 failing with check_restart, sets alert and adds a line to alertString
259 along with any output from the command. Check results, counts, and
260 alertString reflect any checks rerun by check_restart.
261  
262 =head1 METHODS
263  
264 =head2 new
265  
266 Initiates the object.
267  
268 One argument is taken and that is a hash ref. If the key 'config'
269 is present, that will be the config file used. Otherwise
270 '/usr/local/etc/sneck.conf' is used. The key 'include' is a Perl
271 boolean for if the raw config should be included in the JSON.
272  
273 This function should always work as long as it can read the config.
274 If there is an error with parsing or the like, it will be reported
275 in the expected format when $sneck->run is called.
276  
277 This is meant to be rock solid and always work, meaning LibreNMS
278 style JSON is always returned(provided Perl and the other modules
279 are working).
280  
281 If 'debug' is true, when run is called, debugging info will be
282 printed.
283  
284 If 'restart' is true, restarts whose checks failed are run. Otherwise
285 they are only reported. Never enable this for something polled by snmpd.
286  
287 'state_file' is where restart state, used for min_interval and
288 max_retries, is kept. Default :: /var/cache/sneck.cache.restarts
289  
290 'compliance_state_file' is where compliance check state, used for
291 interval, is kept. It is only read or written if a compliance check has
292 a interval. Default :: /var/cache/sneck.cache.compliance
293  
294 'check_timeout', 'check_timeout_signal', and 'check_kill_sub_pids'
295 override the options of the same names in the config. See OPTIONS in
296 L<Monitoring::Sneck::Config>. 'check_timeout_signal' may also be 'none'
297 to send no signal even if the config sets one. Bad values are reported
298 the same as config errors.
299  
300 my $sneck;
301 eval{
302 $sneck=Monitoring::Sneck->new({config=>$file, include=>0, debug=>0, restart=>0});
303 };
304 if ($@){
305 die($@);
306 }
307  
308 =cut
309  
310 199 ▶sub new {
Subroutine new: called CC=20 SCAR=30.0
Pod documented
311 199 my %args;
312 199 ▶ if ( defined( $_[1] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[1]) 198 1 199
313 198 %args = %{ $_[1] };
314 }
315  
316 # init the object
317  
318 199 my $self = {
319  
320 config => '/usr/local/etc/sneck.conf',
321 to_return => {
322 error => 0,
323 errorString => '',
324 data => {
325 hostname => hostname,
326 ok => 0,
327 warning => 0,
328 critical => 0,
329 unknown => 0,
330 errored => 0,
331 alert => 0,
332 alertString => '',
333 checks => {},
334 debugs => {},
335 restarts => {},
336 restarted => 0,
337 compliance => {},
338 compliance_ok => 0,
339 compliance_warning => 0,
340 compliance_critical => 0,
341 compliance_unknown => 0,
342 compliance_errored => 0,
343 compliance_waived => 0,
344 compliance_alert => 0,
345 compliance_alertString => '',
346 compliance_score => undef,
347 compliance_frameworks => {},
348 },
349 version => 1,
350 },
351 parsed_config => undef,
352 good => 1,
353 debug => 0,
354 restart => 0,
355 state_file => '/var/cache/sneck.cache.restarts',
356 compliance_state_file => '/var/cache/sneck.cache.compliance',
357 # if compliance checks also set alert and add to alertString
358 compliance_alert => 0,
359 # same defaults as timeout, timeout_signal, and kill_sub_pids for restarts
360 check_timeout => 30,
361 check_timeout_signal => undef,
362 check_kill_sub_pids => 1,
363 # alertString lines from failed restarts, added after the checks by _tally_checks
364 restart_alerts => [],
365 };
366 199 bless $self;
367  
368 199 ▶ if ( defined( $args{config} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"config"}) 197 2 199
369 197 $self->{config} = $args{config};
370 }
371  
372 199 ▶ if ( defined( $args{debug} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"debug"}) 3 196 199
373 3 $self->{debug} = $args{debug};
374 }
375  
376 199 ▶ if ( defined( $args{restart} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"restart"}) 84 115 199
377 84 $self->{restart} = $args{restart};
378 }
379  
380 199 ▶ if ( defined( $args{state_file} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"state_file"}) 110 89 199
381 110 $self->{state_file} = $args{state_file};
382 }
383  
384 199 ▶ if ( defined( $args{compliance_state_file} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"compliance_state_file"}) 47 152 199
385 47 $self->{compliance_state_file} = $args{compliance_state_file};
386 }
387  
388 199 my $parsed_config;
389 199 eval { $parsed_config = Monitoring::Sneck::Config->new( { file => $self->{config} } ); };
390 199 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 6 193 199
391 6 $self->{good} = 0;
392 6 $self->{to_return}{error} = 1;
393 6 $self->{to_return}{errorString} = $@;
394 6 return $self;
395 }
396  
397 # include the config file if requested
398 193 ▶ if ( defined( $args{include} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{"include"} and $args{"include"}) 5 188 193
Condition100%3/3
defined $args{"include"} and $args{"include"}
!ll&&!rl&&r
18715
MC/DC100%2/2
defined $args{"include"} and $args{"include"}
defined $args{"include"} $args{"include"}
Truth table100%3/3
A and B
A= defined $args{"include"}B= $args{"include"}
ABresult
0X0
100
111
399 && $args{include} )
400 {
401 5 $self->{to_return}{data}{config} = $parsed_config->raw;
402 }
403  
404 193 ▶ if ( !$parsed_config->is_valid ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($parsed_config->is_valid) 7 186 193
405 7 $self->{good} = 0;
406 7 $self->{to_return}{error} = 1;
407 $self->{to_return}{errorString} = join( '; ',
408 7 map { $_->{where} . ': ' . $_->{message} } $parsed_config->errors );
409 7 return $self;
410 }
411  
412 # check timeout settings, args over the config over the defaults
413 186 my $options = $parsed_config->options;
414 186 ▶ if ( defined( $options->{compliance_alert} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{"compliance_alert"}) 3 183 186
415 3 $self->{compliance_alert} = $options->{compliance_alert};
416 }
417 186 my @arg_errors;
418 186 foreach my $name ( 'check_timeout', 'check_timeout_signal', 'check_kill_sub_pids' ) {
419 558 ▶ if ( defined( $options->{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $options->{$name}) 30 528 558
420 30 $self->{$name} = $options->{$name};
421 }
422 558 ▶ if ( !defined( $args{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $args{$name}) 542 16 558
423 542 next;
424 }
425 16 ▶ if ( $name eq 'check_timeout_signal' && $args{$name} eq 'none' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "check_timeout_signal" and $args{$name} eq "none") 3 13 16
Condition100%3/3
$name eq "check_timeout_signal" and $args{$name} eq "none"
!ll&&!rl&&r
943
MC/DC100%2/2
$name eq "check_timeout_signal" and $args{$name} eq "none"
$name eq "check_timeout_signal" $args{$name} eq "none"
Truth table100%3/3
A and B
A= $name eq "check_timeout_signal"B= $args{$name} eq "none"
ABresult
0X0
100
111
426 3 $self->{$name} = undef;
427 3 next;
428 }
429 13 my ( $value, $error ) = Monitoring::Sneck::Config->validate_option( $name, $args{$name} );
430 13 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 5 8 13
431 5 push( @arg_errors, 'arg ' . $name . ': ' . $error );
432 5 next;
433 }
434 8 $self->{$name} = $value;
435 } ## end foreach my $name ( 'check_timeout', 'check_timeout_signal', 'check_kill_sub_pids' )
436 186 ▶ if ( defined( $arg_errors[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg_errors[0]) 2 184 186
437 2 $self->{good} = 0;
438 2 $self->{to_return}{error} = 1;
439 2 $self->{to_return}{errorString} = join( '; ', @arg_errors );
440 2 return $self;
441 }
442  
443 # only touch %ENV once the whole config is known to be good
444 184 foreach my $env ( @{ $parsed_config->env } ) {
445 4 $ENV{ $env->[0] } = $env->[1];
446 }
447  
448 184 $self->{parsed_config} = $parsed_config;
449  
450 184 $self;
451 } ## end sub new
452  
453 =head2 run
454  
455 This runs the checks and returns the return hash.
456  
457 my $return=$sneck->run;
458  
459 =cut
460  
461 202 ▶sub run {
Subroutine run: called CC=10 SCAR=23.0
Pod documented
462 202 my $self = $_[0];
463  
464 202 my $run_start_time = Time::HiRes::time;
465 202 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 1 201 202
466 1 warn( 'run started at ' . $run_start_time );
467 }
468  
469 # if something went wrong with new, just return
470 202 ▶ if ( !$self->{good} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"good"}) 8 194 202
471 8 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 0 8 8
472 0 warn('$self->{good} false... returning $self->{to_return}');
473 }
474 8 return $self->{to_return};
475 }
476  
477 # reset the results so calling run more than once does not accumulate
478 194 $self->{to_return}{data}{ok} = 0;
479 194 $self->{to_return}{data}{warning} = 0;
480 194 $self->{to_return}{data}{critical} = 0;
481 194 $self->{to_return}{data}{unknown} = 0;
482 194 $self->{to_return}{data}{errored} = 0;
483 194 $self->{to_return}{data}{alert} = 0;
484 194 $self->{to_return}{data}{alertString} = '';
485 194 $self->{to_return}{data}{checks} = {};
486 194 $self->{to_return}{data}{debugs} = {};
487 194 $self->{to_return}{data}{restarts} = {};
488 194 $self->{to_return}{data}{restarted} = 0;
489 194 $self->{to_return}{data}{compliance} = {};
490 194 delete( $self->{to_return}{data}{restart_state_error} );
491 194 delete( $self->{to_return}{data}{compliance_state_error} );
492 194 $self->{restart_alerts} = [];
493  
494 # set the time it ran
495 194 $self->{to_return}{data}{time} = time;
496 #make sure it is a int
497 194 $self->{to_return}{data}{time} =~ s/\..*$//;
498  
499 # debugs first, then checks, each in name order
500 194 my $parsed_config = $self->{parsed_config};
501 194 my @to_run;
502 194 foreach my $type ( 'debugs', 'checks' ) {
503 388 my $commands = $parsed_config->$type;
504 388 foreach my $name ( sort( keys( %{$commands} ) ) ) {
505 242 push( @to_run, [ $type, $name, $commands->{$name} ] );
506 }
507 }
508  
509 194 foreach my $item (@to_run) {
510 242 $self->_run_check( @{$item} );
511 }
512  
513 194 $self->_run_compliance;
514  
515 194 $self->_handle_restarts;
516  
517 194 $self->_tally_checks;
518  
519 # after the checks, as it may add to alert and alertString
520 194 $self->_tally_compliance;
521  
522 194 $self->{to_return}{data}{vars} = $parsed_config->vars;
523  
524 # figure out how long the run took
525 194 my $run_stop_time = Time::HiRes::time;
526 194 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 1 193 194
527 1 warn( 'run finished at ' . $run_stop_time );
528 }
529  
530 194 my $run_time = $run_stop_time - $run_start_time;
531 194 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 1 193 194
532 1 warn( 'run time was ' . $run_time );
533 }
534  
535 # round to the 9th place to avoid scientific notation
536 194 $self->{to_return}{data}{run_time} = sprintf( '%.9f', $run_time );
537  
538 194 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 1 193 194
539 1 warn('run is returning now');
540 }
541 194 return $self->{to_return};
542 } ## end sub run
543  
544 # Runs a single check, debug check, or compliance check and stores its
545 # results, replacing any earlier results for it. Used by run, by
546 # _run_compliance, and by _run_restart to rerun checks for check_restart. Does not count it towards ok, warning, and the like.
547 # That is done by _tally_checks once everything has run.
548 #
549 # It is run via _run_command using check_timeout, unless a timeout is given,
550 # check_timeout_signal, and check_kill_sub_pids. A timeout gives a exit of
551 # -1 and a error. A command starting with perl: is run via _run_perl_check
552 # instead, with the same timeout.
553 #
554 # Args...
555 #
556 # - type :: Either 'checks', 'debugs', or 'compliance'.
557 #
558 # - name :: The name of the check.
559 #
560 # - check :: The command, before variable substitution.
561 #
562 # - timeout :: Optional. Seconds to wait on it, used in place of
563 # check_timeout. undef or not given uses check_timeout.
564 #
565 # Returns nothing. Results go in $self->{to_return}{data}{$type}{$name} as
566 # a hash ref of check, ran, output, exit, error if any, and run_time, as
567 # described under RETURN HASH.
568 #
569 # Example...
570 #
571 # $self->_run_check( 'checks', 'http_check', '/usr/local/libexec/nagios/check_http -H %HOST%' );
572 # # $self->{to_return}{data}{checks}{http_check} is
573 # # { check => '...', ran => '...', output => 'HTTP OK...', exit => 0, run_time => '0.012345678' }
574 #
575 # $self->_run_check( 'compliance', 'pkg_vulns', '/usr/local/libexec/nagios/check_pkg_audit', 300 );
576 # # same, but in $self->{to_return}{data}{compliance}{pkg_vulns} and waits up to 300 seconds
577 270 ▶sub _run_check {
Subroutine _run_check: called CC=13 SCAR=25.6
578 270 my ( $self, $type, $name, $check, $timeout ) = @_;
579 270 ▶ if ( !defined($timeout) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $timeout) 269 1 270
580 269 $timeout = $self->{check_timeout};
581 }
582  
583 270 my $check_start_time = Time::HiRes::time;
584 270 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 268 270
585 2 warn( $name . ' processing started at ' . $check_start_time );
586 2 warn( $name . ' is of type ' . $type );
587 }
588  
589 270 my $result = { check => $check };
590 270 $self->{to_return}{data}{$type}{$name} = $result;
591  
592 270 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 268 270
593 2 warn( $name . ' check string: "' . $check . '"' );
594 }
595  
596 # put the variables in place
597 270 $check = $self->{parsed_config}->substitute($check);
598 270 $result->{ran} = $check;
599 270 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 268 270
600 2 warn( $name . ' check string post variable replacement: "' . $check . '"' );
601 }
602  
603 270 my $command_result;
604 270 ▶ if ( $check =~ /^perl:/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($check =~ /^perl:/) { } 1 269 270
605 1 $command_result = $self->_run_perl_check( $check, $timeout );
606 } else {
607 $command_result = $self->_run_command( $check, $timeout, $self->{check_timeout_signal},
608 269 $self->{check_kill_sub_pids} );
609 }
610 270 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 268 270
611 2 warn( $name . ' command done... output is... "' . $command_result->{output} . '"' );
612 }
613  
614 # exit is -1 for timeouts and failing to execute, and 128 + signal for
615 # signal deaths, so neither is mistaken for a nagios exit code of 0 to 3
616 270 my $exit_code = $command_result->{exit};
617 270 $result->{output} = $command_result->{output};
618 270 ▶ if ( defined( $command_result->{wait_status} ) && ( $command_result->{wait_status} & 127 ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $command_result->{'wait_status'} and $command_result->{'wait_status'} & 127) { } 5 265 270
elsif (defined $command_result->{'error'}) { } 17 248 265
Condition100%3/3
defined $command_result->{"wait_status"} and $command_result->{"wait_status"} & 127
!ll&&!rl&&r
172485
MC/DC100%2/2
defined $command_result->{"wait_status"} and $command_result->{"wait_status"} & 127
defined $command_result->{"wait_status"} $command_result->{"wait_status"} & 127
Truth table100%3/3
A and B
A= defined $command_result->{"wait_status"}B= $command_result->{"wait_status"} & 127
ABresult
0X0
100
111
619 $result->{error} = sprintf(
620 "child died with signal %d, %s coredump\n",
621 ( $command_result->{wait_status} & 127 ),
622 5 ▶ ( $command_result->{wait_status} & 128 ) ? 'with' : 'without'
Branch: 1 branch
BranchTrueFalseTotal
$command_result->{'wait_status'} & 128 ? : 1 4 5
623 );
624 } elsif ( defined( $command_result->{error} ) ) {
625 17 $result->{error} = $command_result->{error};
626 }
627 270 $result->{exit} = $exit_code;
628  
629 270 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 268 270
630 2 warn( $name . ' exit code is ' . $exit_code );
631 }
632  
633 # figure out how long the run took
634 270 my $check_stop_time = Time::HiRes::time;
635 270 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 268 270
636 2 warn( $name . ' finished at ' . $check_stop_time );
637 }
638 # round to the 9th place to avoid scientific notation
639 270 $result->{run_time} = sprintf( '%.9f', $check_stop_time - $check_start_time );
640  
641 270 return;
642 } ## end sub _run_check
643  
644 # Counts the check results into ok, warning, critical, unknown, and
645 # errored, and builds alert and alertString from them. Anything other than
646 # exit 0 sets alert. Output of warning, critical, and unknown checks is
647 # added to alertString in name order, followed by the lines for failed
648 # restarts in $self->{restart_alerts}, which also set alert. Called by run
649 # once checks and restarts are done, so rerun checks are counted with
650 # their final results.
651 #
652 # Takes no args and returns nothing. Results go in $self->{to_return}{data}.
653 #
654 # Example...
655 #
656 # # http_check exited 2 and php_check exited 0
657 # $self->_tally_checks;
658 # # ok is 1, critical is 1, alert is 1, and alertString is the output of http_check plus "\n"
659 194 ▶sub _tally_checks {
Subroutine _tally_checks: called CC=9 SCAR=22.0
660 194 my $self = $_[0];
661  
662 194 my $data = $self->{to_return}{data};
663 194 my %counts_by_exit = ( 0 => 'ok', 1 => 'warning', 2 => 'critical', 3 => 'unknown' );
664 194 foreach my $count ( 'ok', 'warning', 'critical', 'unknown', 'errored' ) {
665 970 $data->{$count} = 0;
666 }
667 194 $data->{alert} = 0;
668 194 $data->{alertString} = '';
669  
670 194 foreach my $name ( sort( keys( %{ $data->{checks} } ) ) ) {
671 233 my $exit_code = $data->{checks}{$name}{exit};
672 233 ▶ my $count = defined( $counts_by_exit{$exit_code} ) ? $counts_by_exit{$exit_code} : 'errored';
Branch: 1 branch
BranchTrueFalseTotal
defined $counts_by_exit{$exit_code} ? : 208 25 233
673 233 $data->{$count}++;
674 233 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 2 231 233
675 2 warn( $name . ' is ' . $count );
676 }
677 233 ▶ if ( $count ne 'ok' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count ne "ok") 155 78 233
678 155 $data->{alert} = 1;
679 }
680 # add it to the alert string if it is a warning, critical, or unknown
681 233 ▶ if ( $count ne 'ok' && $count ne 'errored' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count ne "ok" and $count ne "errored") 130 103 233
Condition100%3/3
$count ne "ok" and $count ne "errored"
!ll&&!rl&&r
7825130
MC/DC100%2/2
$count ne "ok" and $count ne "errored"
$count ne "ok" $count ne "errored"
Truth table100%3/3
A and B
A= $count ne "ok"B= $count ne "errored"
ABresult
0X0
100
111
682 130 $data->{alertString} = $data->{alertString} . $data->{checks}{$name}{output} . "\n";
683 }
684 } ## end foreach my $name ( sort( keys( %{ $data->{checks} } ) ) )
685  
686 194 foreach my $line ( @{ $self->{restart_alerts} } ) {
687 19 $data->{alert} = 1;
688 19 $data->{alertString} = $data->{alertString} . $line;
689 }
690  
691 194 return;
692 } ## end sub _tally_checks
693  
694 # Runs the compliance checks in name order and stores their results in
695 # $self->{to_return}{data}{compliance}. Called by run after the checks.
696 # Does not count them. That is done by _tally_compliance.
697 #
698 # A compliance check with a interval is only run if it has no saved result,
699 # its command after variable substitution has changed, or interval seconds
700 # have passed since it last ran. Otherwise the saved result is used, with
701 # cached set to 1. Saved results are kept in the compliance state file, which
702 # is only read and written if at least one has a interval. Problems with it
703 # go in data.compliance_state_error, and everything is just run.
704 #
705 # Each result also gets last_ran, cached, waived, plus control, framework,
706 # severity, waived_until, and waiver if set. waived is worked out every run
707 # from the current config, so a waiver that has expired stops applying even
708 # to a cached result.
709 #
710 # Takes no args and returns nothing.
711 #
712 # Example...
713 #
714 # # ssh_no_root, with control=CIS-5.2.10 severity=high, exited 2
715 # $self->_run_compliance;
716 # # $self->{to_return}{data}{compliance}{ssh_no_root} is
717 # # { check => '...', ran => '...', output => '...', exit => 2, run_time => '0.012345678',
718 # # last_ran => 1791491419, cached => 0, waived => 0, control => 'CIS-5.2.10', severity => 'high' }
719 194 ▶sub _run_compliance {
Subroutine _run_compliance: called CC=21 SCAR=30.5
720 194 my $self = $_[0];
721  
722 194 my $data = $self->{to_return}{data};
723 194 my $compliance = $self->{parsed_config}->compliance;
724 194 my @names = sort( keys( %{$compliance} ) );
725 194 ▶ if ( !defined( $names[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $names[0]) 178 16 194
726 178 return;
727 }
728  
729 16 my $uses_interval = grep { $compliance->{$_}{interval} > 0 } @names;
730 16 my $state = {};
731 16 my $state_error;
732 16 ▶ if ($uses_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uses_interval) 8 8 16
733 8 ( $state, $state_error ) = $self->_read_compliance_state;
734 }
735  
736 16 my %new_state;
737 16 foreach my $name (@names) {
738 23 my $item = $compliance->{$name};
739 23 my $ran = $self->{parsed_config}->substitute( $item->{command} );
740 23 my $now = int(time);
741 23 my $saved = $state->{$name};
742  
743 23 ▶ if ( $item->{interval} > 0
Branch: 1 branch
BranchTrueFalseTotal
if ($item->{'interval'} > 0 and defined $saved and $saved->{'result'}{'ran'} eq $ran and $now >= $saved->{'last_ran'} and $now - $saved->{'last_ran'} < $item->{'interval'}) { } 3 20 23
Condition91%11/12
$item->{"interval"} > 0 and defined $saved and $saved->{"result"}{"ran"} eq $ran and $now >= $saved->{"last_ran"} and $now - $saved->{"last_ran"} < $item->{"interval"}
!ll&&!rl&&r
1913
$item->{"interval"} > 0 and defined $saved and $saved->{"result"}{"ran"} eq $ran and $now >= $saved->{"last_ran"}
!ll&&!rl&&r
1904
$item->{"interval"} > 0 and defined $saved and $saved->{"result"}{"ran"} eq $ran
!ll&&!rl&&r
1814
$item->{"interval"} > 0 and defined $saved
!ll&&!rl&&r
1535
MC/DC80%4/5
$item->{"interval"} > 0 and defined $saved and $saved->{"result"}{"ran"} eq $ran and $now >= $saved->{"last_ran"} and $now - $saved->{"last_ran"} < $item->{"interval"}
$item->{"interval"} > 0 defined $saved $saved->{"result"}{"ran"} eq $ran $now >= $saved->{"last_ran"} $now - $saved->{"last_ran"} < $item->{"interval"}
Truth table83%5/6
A and B and C and D and E
A= $item->{"interval"} > 0B= defined $savedC= $saved->{"result"}{"ran"} eq $ranD= $now >= $saved->{"last_ran"}E= $now - $saved->{"last_ran"} < $item->{"interval"}
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
744 && defined($saved)
745 && $saved->{result}{ran} eq $ran
746 && $now >= $saved->{last_ran}
747 && $now - $saved->{last_ran} < $item->{interval} )
748 {
749 3 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 0 3 3
750 0 warn( $name . ' compliance check is cached from ' . $saved->{last_ran} );
751 }
752 $data->{compliance}{$name} = {
753 3 %{ $saved->{result} },
754 check => $item->{command},
755 last_ran => $saved->{last_ran},
756 3 cached => 1,
757 };
758 } else {
759 20 $self->_run_check( 'compliance', $name, $item->{command}, $item->{timeout} );
760 20 $data->{compliance}{$name}{last_ran} = $now;
761 20 $data->{compliance}{$name}{cached} = 0;
762 }
763 23 my $result = $data->{compliance}{$name};
764  
765 23 ▶ if ( $item->{interval} > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($item->{"interval"} > 0) 8 15 23
766 8 my %saved_result;
767 8 foreach my $key ( 'ran', 'output', 'exit', 'error', 'run_time' ) {
768 40 ▶ if ( defined( $result->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result->{$key}) 32 8 40
769 32 $saved_result{$key} = $result->{$key};
770 }
771 }
772 8 $new_state{$name} = { last_ran => $result->{last_ran}, result => \%saved_result };
773 }
774  
775 23 foreach my $key ( 'control', 'framework', 'severity', 'waived_until', 'waiver' ) {
776 115 ▶ if ( defined( $item->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $item->{$key}) 14 101 115
777 14 $result->{$key} = $item->{$key};
778 }
779 }
780  
781 # errored is never waived, as that means the check itself is broken
782 23 $result->{waived} = 0;
783 23 ▶ if ( defined( $item->{waived_until} )
Branch: 1 branch
BranchTrueFalseTotal
if (defined $item->{"waived_until"} and $result->{"exit"} >= 1 and $result->{"exit"} <= 3 and POSIX::strftime("%Y-%m-%d", localtime &Monitoring::Sneck::time()) le $item->{"waived_until"}) 2 21 23
Condition100%9/9
defined $item->{"waived_until"} and $result->{"exit"} >= 1 and $result->{"exit"} <= 3 and POSIX::strftime("%Y-%m-%d", localtime &Monitoring::Sneck::time()) le $item->{"waived_until"}
!ll&&!rl&&r
2012
defined $item->{"waived_until"} and $result->{"exit"} >= 1 and $result->{"exit"} <= 3
!ll&&!rl&&r
1913
defined $item->{"waived_until"} and $result->{"exit"} >= 1
!ll&&!rl&&r
1814
MC/DC100%4/4
defined $item->{"waived_until"} and $result->{"exit"} >= 1 and $result->{"exit"} <= 3 and POSIX::strftime("%Y-%m-%d", localtime &Monitoring::Sneck::time()) le $item->{"waived_until"}
defined $item->{"waived_until"} $result->{"exit"} >= 1 $result->{"exit"} <= 3 POSIX::strftime("%Y-%m-%d", localtime &Monitoring::Sneck::time()) le $item->{"waived_until"}
Truth table100%5/5
A and B and C and D
A= defined $item->{"waived_until"}B= $result->{"exit"} >= 1C= $result->{"exit"} <= 3D= POSIX::strftime("%Y-%m-%d", localtime &Monitoring::Sneck::time()) le $item->{"waived_until"}
ABCDresult
0XXX0
10XX0
110X0
11100
11111
784 && $result->{exit} >= 1
785 && $result->{exit} <= 3
786 && POSIX::strftime( '%Y-%m-%d', localtime(time) ) le $item->{waived_until} )
787 {
788 2 $result->{waived} = 1;
789 }
790 } ## end foreach my $name (@names)
791  
792 16 ▶ if ($uses_interval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uses_interval) 8 8 16
793 8 my $write_error = $self->_write_compliance_state( \%new_state );
794 8 my @state_errors = grep { defined($_) } ( $state_error, $write_error );
795 8 ▶ if ( defined( $state_errors[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $state_errors[0]) 2 6 8
796 2 $data->{compliance_state_error} = join( '; ', @state_errors );
797 }
798 }
799  
800 16 return;
801 } ## end sub _run_compliance
802  
803 # Counts the compliance check results into compliance_ok,
804 # compliance_warning, compliance_critical, compliance_unknown,
805 # compliance_errored, and compliance_waived, along with the same counts per
806 # framework in compliance_frameworks. Waived ones only count as waived.
807 # Anything not ok or waived sets compliance_alert. Output of warning,
808 # critical, and unknown ones is added to compliance_alertString in name
809 # order, prefixed with the control, or the name if there is none, and the
810 # severity if set. Scores are worked out via _compliance_score.
811 #
812 # If the compliance_alert option is set, compliance_alert also sets alert
813 # and compliance_alertString is added to the end of alertString. Called by
814 # run after _tally_checks, so this is not overwritten.
815 #
816 # Takes no args and returns nothing. Results go in $self->{to_return}{data}.
817 #
818 # Example...
819 #
820 # # ssh_no_root, with control=CIS-5.2.10 framework=CIS severity=high, exited 2
821 # # and shadow_perms, with framework=CIS, exited 0
822 # $self->_tally_compliance;
823 # # compliance_ok is 1, compliance_critical is 1, compliance_alert is 1,
824 # # compliance_score is 50, compliance_alertString is "[CIS-5.2.10 high] $output\n",
825 # # and compliance_frameworks is { CIS => { ok => 1, critical => 1, score => 50, ... } }
826 194 ▶sub _tally_compliance {
Subroutine _tally_compliance: called CC=17 SCAR=28.3
827 194 my $self = $_[0];
828  
829 194 my $data = $self->{to_return}{data};
830 194 my %counts_by_exit = ( 0 => 'ok', 1 => 'warning', 2 => 'critical', 3 => 'unknown' );
831 194 my @count_names = ( 'ok', 'warning', 'critical', 'unknown', 'errored', 'waived' );
832 194 my %totals = map { $_ => 0 } @count_names;
833 194 my %frameworks;
834 194 my $alert_string = '';
835  
836 194 foreach my $name ( sort( keys( %{ $data->{compliance} } ) ) ) {
837 23 my $result = $data->{compliance}{$name};
838 23 my $count = 'errored';
839 23 ▶ if ( $result->{waived} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($result->{'waived'}) { } 2 21 23
elsif (defined $counts_by_exit{$result->{'exit'}}) { } 18 3 21
840 2 $count = 'waived';
841 } elsif ( defined( $counts_by_exit{ $result->{exit} } ) ) {
842 18 $count = $counts_by_exit{ $result->{exit} };
843 }
844 23 $totals{$count}++;
845 23 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 0 23 23
846 0 warn( $name . ' compliance check is ' . $count );
847 }
848  
849 23 ▶ if ( defined( $result->{framework} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result->{"framework"}) 3 20 23
850 3 ▶ if ( !defined( $frameworks{ $result->{framework} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $frameworks{$result->{"framework"}}) 2 1 3
851 2 $frameworks{ $result->{framework} } = { map { $_ => 0 } @count_names };
852 }
853 3 $frameworks{ $result->{framework} }{$count}++;
854 }
855  
856 23 ▶ if ( $count eq 'warning' || $count eq 'critical' || $count eq 'unknown' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count eq "warning" or $count eq "critical" or $count eq "unknown") 7 16 23
Condition100%6/6
$count eq "warning" or $count eq "critical" or $count eq "unknown"
l!l&&r!l&&!r
6116
$count eq "warning" or $count eq "critical"
l!l&&r!l&&!r
1517
MC/DC100%3/3
$count eq "warning" or $count eq "critical" or $count eq "unknown"
$count eq "warning" $count eq "critical" $count eq "unknown"
Truth table100%4/4
A or B or C
A= $count eq "warning"B= $count eq "critical"C= $count eq "unknown"
ABCresult
1XX1
01X1
0011
0000
857 7 ▶ my $prefix = defined( $result->{control} ) ? $result->{control} : $name;
Branch: 1 branch
BranchTrueFalseTotal
defined $result->{'control'} ? : 3 4 7
858 7 ▶ if ( defined( $result->{severity} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result->{"severity"}) 2 5 7
859 2 $prefix = $prefix . ' ' . $result->{severity};
860 }
861 7 $alert_string = $alert_string . '[' . $prefix . '] ' . $result->{output} . "\n";
862 }
863 } ## end foreach my $name ( sort( keys( %{ $data->{compliance} } ) ) )
864  
865 194 foreach my $count (@count_names) {
866 1164 $data->{ 'compliance_' . $count } = $totals{$count};
867 }
868 194 $data->{compliance_score} = $self->_compliance_score( \%totals );
869 194 foreach my $framework ( keys(%frameworks) ) {
870 2 $frameworks{$framework}{score} = $self->_compliance_score( $frameworks{$framework} );
871 }
872 194 $data->{compliance_frameworks} = \%frameworks;
873 194 $data->{compliance_alertString} = $alert_string;
874 $data->{compliance_alert}
875 194 ▶ = ( $totals{warning} + $totals{critical} + $totals{unknown} + $totals{errored} ) > 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$totals{'warning'} + $totals{'critical'} + $totals{'unknown'} + $totals{'errored'} > 0 ? : 6 188 194
876  
877 194 ▶ if ( $self->{compliance_alert} && $data->{compliance_alert} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"compliance_alert"} and $data->{"compliance_alert"}) 2 192 194
Condition100%3/3
$self->{"compliance_alert"} and $data->{"compliance_alert"}
!ll&&!rl&&r
19112
MC/DC100%2/2
$self->{"compliance_alert"} and $data->{"compliance_alert"}
$self->{"compliance_alert"} $data->{"compliance_alert"}
Truth table100%3/3
A and B
A= $self->{"compliance_alert"}B= $data->{"compliance_alert"}
ABresult
0X0
100
111
878 2 $data->{alert} = 1;
879 2 $data->{alertString} = $data->{alertString} . $alert_string;
880 }
881  
882 194 return;
883 } ## end sub _tally_compliance
884  
885 # Works out the percent of compliance checks that passed, leaving out
886 # waived ones. Used by _tally_compliance.
887 #
888 # Args...
889 #
890 # - counts :: Hash ref of ok, warning, critical, unknown, errored, and
891 # waived counts.
892 #
893 # Returns the percent ok, rounded to two decimal places, as a number, or
894 # undef if there is nothing to score, such as when all are waived.
895 #
896 # Example...
897 #
898 # $self->_compliance_score( { ok => 2, warning => 0, critical => 1, unknown => 0, errored => 0, waived => 1 } );
899 # # returns 66.67
900 #
901 # $self->_compliance_score( { ok => 0, warning => 0, critical => 0, unknown => 0, errored => 0, waived => 2 } );
902 # # returns undef
903 196 ▶sub _compliance_score {
Subroutine _compliance_score: called CC=3 SCAR=11.0
904 196 my ( $self, $counts ) = @_;
905  
906 196 my $scored = 0;
907 196 foreach my $count ( 'ok', 'warning', 'critical', 'unknown', 'errored' ) {
908 980 $scored = $scored + $counts->{$count};
909 }
910 196 ▶ if ( $scored == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($scored == 0) 179 17 196
911 179 return undef;
912 }
913  
914 17 return sprintf( '%.2f', $counts->{ok} / $scored * 100 ) + 0;
915 } ## end sub _compliance_score
916  
917 # Works out which restarts triggered and, if restarts are enabled, runs
918 # them. Called by run after all checks have run and before _tally_checks.
919 # Takes no args and returns nothing. Results go in
920 # $self->{to_return}{data}{restarts} and $self->{to_return}{data}{restarted},
921 # and failures are added to $self->{restart_alerts}. Which restarts
922 # triggered is worked out once, before any run, so checks rerun by
923 # check_restart do not change it for the restarts after.
924 #
925 # Restarts run in dependency order. A restart runs if its threshold was
926 # met, or if cascade is set and one of its depends ran without failing.
927 # Before running, it is skipped if a depend failed or was itself skipped
928 # for that reason, and held back by not_every, min_interval and, for
929 # threshold triggered runs, max_retries. One held back by not_every gets no
930 # status, so restarts depending on it act as if it did not trigger, and its
931 # state is left alone. State for min_interval and max_retries is kept in
932 # the state file. It is written before each restart runs, so a run that is killed
933 # part way through still counts, and again once all are done. last_run is
934 # set to when each restart finished.
935 #
936 # Example...
937 #
938 # # http_check exited 2 and httpd watches it with the default threshold of 1
939 # $self->_handle_restarts;
940 # # $self->{to_return}{data}{restarts}{httpd} is
941 # # { triggered => 1, ran => 1, reason => 'threshold', failed_checks => ['http_check'],
942 # # threshold => 1, attempts => 1, command => '...', ran_command => '...',
943 # # output => '...', exit => 0, run_time => '1.234567890' }
944 194 ▶sub _handle_restarts {
Subroutine _handle_restarts: called CC=33 SCAR=35.0
945 194 my $self = $_[0];
946  
947 194 my $data = $self->{to_return}{data};
948 194 my $restarts = $self->{parsed_config}->restarts;
949 194 my @names = sort( keys( %{$restarts} ) );
950 194 ▶ if ( !defined( $names[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $names[0]) 93 101 194
951 93 return;
952 }
953  
954 101 foreach my $name (@names) {
955 150 my $restart = $restarts->{$name};
956 150 my @failed_checks = grep { $self->_check_failed( $data->{checks}{$_}{exit}, $restart ) } @{ $restart->{checks} };
957 $data->{restarts}{$name} = {
958 triggered => scalar(@failed_checks) >= $restart->{threshold} ? 1 : 0,
959 ran => 0,
960 reason => 'not triggered',
961 failed_checks => \@failed_checks,
962 threshold => $restart->{threshold},
963 attempts => 0,
964 command => $restart->{command},
965 150 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
scalar @failed_checks >= $restart->{'threshold'} ? : 121 29 150
966 } ## end foreach my $name (@names)
967  
968 101 ▶ if ( !$self->{restart} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"restart"}) 3 98 101
969 3 foreach my $name (@names) {
970 3 $data->{restarts}{$name}{reason} = 'restarts disabled';
971 }
972 3 return;
973 }
974  
975 98 my ( $state, $state_error ) = $self->_read_restart_state;
976 98 my $write_error;
977  
978 # forget restarts no longer in the config
979 98 foreach my $name ( keys( %{$state} ) ) {
980 40 ▶ if ( !defined( $restarts->{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $restarts->{$name}) 2 38 40
981 2 delete( $state->{$name} );
982 }
983 }
984  
985 # 'ok' or 'failed' for those that ran, 'skipped' for those skipped because a depend failed
986 98 my %status;
987 98 foreach my $name ( $self->_restart_order($restarts) ) {
988 147 my $restart = $restarts->{$name};
989 147 my $result = $data->{restarts}{$name};
990 147 my $now = int(time);
991 147 ▶ if ( !defined( $state->{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $state->{$name}) 109 38 147
992 109 $state->{$name} = { last_run => 0, attempts => 0 };
993 }
994 147 my $state_item = $state->{$name};
995  
996 # the checks recovered, so start counting attempts again
997 147 ▶ if ( !$result->{triggered} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result->{"triggered"}) 29 118 147
998 29 $state_item->{attempts} = 0;
999 }
1000  
1001 147 my $run_reason;
1002 my $cascade_from;
1003 147 ▶ if ( $result->{triggered} ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($result->{'triggered'}) { } 118 29 147
elsif ($restart->{'cascade'}) { } 17 12 29
1004 118 $run_reason = 'threshold';
1005 } elsif ( $restart->{cascade} ) {
1006 17 ▶ ($cascade_from) = grep { defined( $status{$_} ) && $status{$_} eq 'ok' } @{ $restart->{depends} };
Condition100%3/3
defined $status{$_} && $status{$_} eq 'ok'
!ll&&!rl&&r
4114
MC/DC100%2/2
defined $status{$_} && $status{$_} eq 'ok'
defined $status{$_} $status{$_} eq 'ok'
Truth table100%3/3
A && B
A= defined $status{$_}B= $status{$_} eq 'ok'
ABresult
0X0
100
111
1007 17 ▶ if ( defined($cascade_from) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cascade_from) 13 4 17
1008 13 $run_reason = 'cascade from ' . $cascade_from;
1009 }
1010 }
1011  
1012 147 ▶ if ( defined($run_reason) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $run_reason) 131 16 147
1013 my ($failed_depend)
1014 30 ▶ = grep { defined( $status{$_} ) && ( $status{$_} eq 'failed' || $status{$_} eq 'skipped' ) }
Condition100%6/6
defined $status{$_} && ($status{$_} eq 'failed' || $status{$_} eq 'skipped')
!ll&&!rl&&r
6177
$status{$_} eq "failed" or $status{$_} eq "skipped"
l!l&&r!l&&!r
6117
MC/DC100%3/3
defined $status{$_} && ($status{$_} eq 'failed' || $status{$_} eq 'skipped')
defined $status{$_} $status{$_} eq "failed" $status{$_} eq "skipped"
Truth table100%4/4
A && B or C
A= defined $status{$_}B= $status{$_} eq "failed"C= $status{$_} eq "skipped"
ABCresult
0XX0
1000
11X1
1011
1015 131 @{ $restart->{depends} };
1016 131 my $since_last = $now - $state_item->{last_run};
1017 131 ▶ if ( defined($failed_depend) ) {
Branch: 4 branches
BranchTrueFalseTotal
if (defined $failed_depend) { } 7 124 131
elsif (defined $restart->{'not_every'} and $self->_in_not_every($restart->{'not_every'}, $now)) { } 3 121 124
elsif ($restart->{'min_interval'} > 0 and $since_last >= 0 and $since_last < $restart->{'min_interval'}) { } 9 112 121
elsif ($run_reason eq 'threshold' and $restart->{'max_retries'} > 0 and $state_item->{'attempts'} >= $restart->{'max_retries'}) { } 5 107 112
1018 7 $result->{reason} = 'skipped, dependency ' . $failed_depend . ' failed';
1019 7 $status{$name} = 'skipped';
1020 ▶ } elsif ( defined( $restart->{not_every} ) && $self->_in_not_every( $restart->{not_every}, $now ) ) {
Condition100%3/3
defined $restart->{"not_every"} and $self->_in_not_every($restart->{"not_every"}, $now)
!ll&&!rl&&r
12013
MC/DC100%2/2
defined $restart->{"not_every"} and $self->_in_not_every($restart->{"not_every"}, $now)
defined $restart->{"not_every"} $self->_in_not_every($restart->{"not_every"}, $now)
Truth table100%3/3
A and B
A= defined $restart->{"not_every"}B= $self->_in_not_every($restart->{"not_every"}, $now)
ABresult
0X0
100
111
1021 3 $result->{reason} = 'maintenance window';
1022 ▶ } elsif ( $restart->{min_interval} > 0
Condition100%6/6
$restart->{"min_interval"} > 0 and $since_last >= 0 and $since_last < $restart->{"min_interval"}
!ll&&!rl&&r
39739
$restart->{"min_interval"} > 0 and $since_last >= 0
!ll&&!rl&&r
38182
MC/DC100%3/3
$restart->{"min_interval"} > 0 and $since_last >= 0 and $since_last < $restart->{"min_interval"}
$restart->{"min_interval"} > 0 $since_last >= 0 $since_last < $restart->{"min_interval"}
Truth table100%4/4
A and B and C
A= $restart->{"min_interval"} > 0B= $since_last >= 0C= $since_last < $restart->{"min_interval"}
ABCresult
0XX0
10X0
1100
1111
1023 && $since_last >= 0
1024 && $since_last < $restart->{min_interval} )
1025 {
1026 9 $result->{reason} = 'cooldown, ' . ( $restart->{min_interval} - $since_last ) . ' seconds left';
1027 ▶ } elsif ( $run_reason eq 'threshold'
Condition100%6/6
$run_reason eq "threshold" and $restart->{"max_retries"} > 0 and $state_item->{"attempts"} >= $restart->{"max_retries"}
!ll&&!rl&&r
9895
$run_reason eq "threshold" and $restart->{"max_retries"} > 0
!ll&&!rl&&r
138514
MC/DC100%3/3
$run_reason eq "threshold" and $restart->{"max_retries"} > 0 and $state_item->{"attempts"} >= $restart->{"max_retries"}
$run_reason eq "threshold" $restart->{"max_retries"} > 0 $state_item->{"attempts"} >= $restart->{"max_retries"}
Truth table100%4/4
A and B and C
A= $run_reason eq "threshold"B= $restart->{"max_retries"} > 0C= $state_item->{"attempts"} >= $restart->{"max_retries"}
ABCresult
0XX0
10X0
1100
1111
1028 && $restart->{max_retries} > 0
1029 && $state_item->{attempts} >= $restart->{max_retries} )
1030 {
1031 5 $result->{reason} = 'max retries reached';
1032 } else {
1033 # save the run before it starts, so it still counts if sneck dies while it runs
1034 107 $state_item->{last_run} = $now;
1035 107 ▶ if ( $run_reason eq 'threshold' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($run_reason eq "threshold") 94 13 107
1036 94 $state_item->{attempts}++;
1037 }
1038 107 my $error = $self->_write_restart_state($state);
1039 107 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 2 105 107
1040 2 $write_error = $error;
1041 }
1042  
1043 107 $self->_run_restart( $name, $restart, $result, $cascade_from, $state_item->{attempts} );
1044  
1045 # min_interval is counted from when it finished
1046 107 $state_item->{last_run} = int(time);
1047 107 ▶ $status{$name} = defined( $result->{error} ) || $result->{exit} != 0 ? 'failed' : 'ok';
Branch: 1 branch
BranchTrueFalseTotal
defined $result->{'error'} || $result->{'exit'} != 0 ? : 19 88 107
Condition100%3/3
defined $result->{"error"} or $result->{"exit"} != 0
l!l&&r!l&&!r
11888
MC/DC100%2/2
defined $result->{"error"} or $result->{"exit"} != 0
defined $result->{"error"} $result->{"exit"} != 0
Truth table100%3/3
A or B
A= defined $result->{"error"}B= $result->{"exit"} != 0
ABresult
1X1
011
000
1048 } ## end else [ if ( defined($failed_depend) ) ]
1049 } ## end if ( defined($run_reason) )
1050  
1051 147 $result->{attempts} = $state_item->{attempts};
1052 } ## end foreach my $name ( $self->_restart_order($restarts) )
1053  
1054 98 my $error = $self->_write_restart_state($state);
1055 98 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 2 96 98
1056 2 $write_error = $error;
1057 }
1058 98 my @state_errors = grep { defined($_) } ( $state_error, $write_error );
1059 98 ▶ if ( defined( $state_errors[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $state_errors[0]) 5 93 98
1060 5 $data->{restart_state_error} = join( '; ', @state_errors );
1061 }
1062  
1063 98 return;
1064 } ## end sub _handle_restarts
1065  
1066 # Checks if a time falls in a not_every maintenance window. Used by
1067 # _handle_restarts. The time is turned into local time via localtime, so
1068 # TZ is honored, and matched to the minute. DateTime::Event::Cron is only
1069 # loaded the first time this is called.
1070 #
1071 # Args...
1072 #
1073 # - spec :: A five field cron spec, as already validated by
1074 # Monitoring::Sneck::Config.
1075 #
1076 # - epoch :: Unix time to check.
1077 #
1078 # Returns 1 if the time matches the spec, otherwise 0.
1079 #
1080 # Example...
1081 #
1082 # # 2026-10-11 02:30 local time, a Sunday
1083 # $self->_in_not_every( '* 2-3 * * 0', $epoch );
1084 # # returns 1
1085 #
1086 # $self->_in_not_every( '* 4 * * *', $epoch );
1087 # # returns 0
1088 15 ▶sub _in_not_every {
Subroutine _in_not_every: called CC=2 SCAR=6.9
1089 15 my ( $self, $spec, $epoch ) = @_;
1090  
1091 15 require DateTime;
1092 15 require DateTime::Event::Cron;
1093  
1094 # floating, so it is matched as is and DateTime never has to work out the local time zone itself
1095 15 my @local_time = localtime($epoch);
1096 15 my $local_time = DateTime->new(
1097 year => $local_time[5] + 1900,
1098 month => $local_time[4] + 1,
1099 day => $local_time[3],
1100 hour => $local_time[2],
1101 minute => $local_time[1],
1102 time_zone => 'floating',
1103 );
1104  
1105 15 ▶ return DateTime::Event::Cron->new_from_cron( cron => $spec )->match($local_time) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
'DateTime::Event::Cron'->new_from_cron('cron', $spec)->match($local_time) ? : 9 6 15
1106 } ## end sub _in_not_every
1107  
1108 # Runs a single restart and records the results. Used by _handle_restarts.
1109 # The command gets the SNECK_* environment variables described under
1110 # RESTARTS in Monitoring::Sneck::Config. If check_restart is set, its
1111 # checks are then rerun via _run_check after check_restart_delay seconds.
1112 # A failed restart, including its checks still meeting the threshold
1113 # afterwards, adds a line to $self->{restart_alerts}, along with any
1114 # output from the command.
1115 #
1116 # Args...
1117 #
1118 # - name :: The name of the restart.
1119 #
1120 # - restart :: Hash ref of the restart as returned by the restarts
1121 # method of Monitoring::Sneck::Config.
1122 #
1123 # - result :: Hash ref of the restart's entry in data.restarts, which
1124 # is filled in with ran, reason, ran_command, output, exit, error if
1125 # any, run_time, and recheck_failed_checks if rechecked.
1126 #
1127 # - cascade_from :: Name of the depend it is cascading from, or undef
1128 # if it is running for its threshold.
1129 #
1130 # - attempts :: Runs for its threshold since its checks last
1131 # recovered, this one included. Passed on as SNECK_ATTEMPTS.
1132 #
1133 # Returns nothing.
1134 #
1135 # Example...
1136 #
1137 # $self->_run_restart( 'httpd', $restarts->{httpd}, $data->{restarts}{httpd}, undef, 1 );
1138 # # $data->{restarts}{httpd}{ran} is 1 and $data->{restarted} went up by 1
1139 #
1140 # $self->_run_restart( 'httpd', $restarts->{httpd}, $data->{restarts}{httpd}, 'php_fpm', 0 );
1141 # # same, but reason is 'cascade from php_fpm' and SNECK_REASON was 'cascade'
1142 107 ▶sub _run_restart {
Subroutine _run_restart: called CC=17 SCAR=28.3
1143 107 my ( $self, $name, $restart, $result, $cascade_from, $attempts ) = @_;
1144  
1145 107 ▶ my $reason = defined($cascade_from) ? 'cascade from ' . $cascade_from : 'threshold';
Branch: 1 branch
BranchTrueFalseTotal
defined $cascade_from ? : 13 94 107
1146 107 my $start_time = Time::HiRes::time;
1147 107 my $ran_command = $self->{parsed_config}->substitute( $restart->{command} );
1148 107 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 1 106 107
1149 1 warn( 'restart ' . $name . ' running for ' . $reason . ': "' . $ran_command . '"' );
1150 }
1151  
1152 # tell the command why it is running
1153 my %sneck_env = (
1154 SNECK_RESTART => $name,
1155 SNECK_REASON => defined($cascade_from) ? 'cascade' : 'threshold',
1156 SNECK_CASCADE_FROM => defined($cascade_from) ? $cascade_from : '',
1157 107 SNECK_FAILED_CHECKS => join( ',', @{ $result->{failed_checks} } ),
1158 107 SNECK_CHECKS => join( ',', @{ $restart->{checks} } ),
1159 SNECK_THRESHOLD => $restart->{threshold},
1160 107 ▶ SNECK_ATTEMPTS => $attempts,
Branch: 2 branches
BranchTrueFalseTotal
defined $cascade_from ? : 13 94 107
defined $cascade_from ? : 13 94 107
1161 );
1162 107 my $command_result;
1163 {
1164 107 local @ENV{ keys(%sneck_env) } = values(%sneck_env);
1165 $command_result = $self->_run_command( $ran_command, $restart->{timeout}, $restart->{timeout_signal},
1166 107 $restart->{kill_sub_pids} );
1167 }
1168  
1169 107 $result->{ran} = 1;
1170 107 $result->{reason} = $reason;
1171 107 $result->{ran_command} = $ran_command;
1172 107 $result->{output} = $command_result->{output};
1173 107 $result->{exit} = $command_result->{exit};
1174 107 ▶ if ( defined( $command_result->{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $command_result->{"error"}) 9 98 107
1175 9 $result->{error} = $command_result->{error};
1176 }
1177 107 $result->{run_time} = sprintf( '%.9f', Time::HiRes::time - $start_time );
1178 107 $self->{to_return}{data}{restarted}++;
1179  
1180 107 ▶ if ( $restart->{check_restart} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($restart->{"check_restart"}) 7 100 107
1181 7 ▶ if ( $restart->{check_restart_delay} > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($restart->{"check_restart_delay"} > 0) 1 6 7
1182 1 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 0 1 1
1183 0 warn( 'restart ' . $name . ' waiting ' . $restart->{check_restart_delay} . ' seconds to recheck' );
1184 }
1185 1 sleep( $restart->{check_restart_delay} );
1186 }
1187 7 my $checks = $self->{parsed_config}->checks;
1188 7 foreach my $check_name ( @{ $restart->{checks} } ) {
1189 8 $self->_run_check( 'checks', $check_name, $checks->{$check_name} );
1190 8 $self->{to_return}{data}{checks}{$check_name}{rechecked_by} = $name;
1191 }
1192 8 my @still_failed = grep { $self->_check_failed( $self->{to_return}{data}{checks}{$_}{exit}, $restart ) }
1193 7 @{ $restart->{checks} };
1194 7 $result->{recheck_failed_checks} = \@still_failed;
1195 7 ▶ if ( scalar(@still_failed) >= $restart->{threshold} && !defined( $result->{error} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @still_failed >= $restart->{"threshold"} and not defined $result->{"error"}) 2 5 7
Condition66%2/3
scalar @still_failed >= $restart->{"threshold"} and not defined $result->{"error"}
!ll&&!rl&&r
502
MC/DC50%1/2
scalar @still_failed >= $restart->{"threshold"} and not defined $result->{"error"}
scalar @still_failed >= $restart->{"threshold"} not defined $result->{"error"}
Truth table66%2/3
A and not(B)
A= scalar @still_failed >= $restart->{"threshold"}B= not defined $result->{"error"}
ABresult
0X0
100
111
1196 2 $result->{error} = 'checks still failing after restart: ' . join( ', ', @still_failed );
1197 }
1198 } ## end if ( $restart->{check_restart} )
1199  
1200 107 ▶ if ( defined( $result->{error} ) || $result->{exit} != 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $result->{"error"} or $result->{"exit"} != 0) 19 88 107
Condition100%3/3
defined $result->{"error"} or $result->{"exit"} != 0
l!l&&r!l&&!r
11888
MC/DC100%2/2
defined $result->{"error"} or $result->{"exit"} != 0
defined $result->{"error"} $result->{"exit"} != 0
Truth table100%3/3
A or B
A= defined $result->{"error"}B= $result->{"exit"} != 0
ABresult
1X1
011
000
1201 19 ▶ my $why = defined( $result->{error} ) ? $result->{error} : 'exit ' . $result->{exit};
Branch: 1 branch
BranchTrueFalseTotal
defined $result->{'error'} ? : 11 8 19
1202 19 ▶ if ( $result->{output} ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result->{"output"} ne "") 9 10 19
1203 9 $why = $why . ': ' . $result->{output};
1204 }
1205 19 push( @{ $self->{restart_alerts} }, 'restart "' . $name . '" failed, ' . $why . "\n" );
1206 }
1207  
1208 107 ▶ if ( $self->{debug} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"debug"}) 1 106 107
1209 1 warn( 'restart ' . $name . ' exit code is ' . $result->{exit} );
1210 }
1211  
1212 107 return;
1213 } ## end sub _run_restart
1214  
1215 # Runs a check or restart command with a timeout and returns its results.
1216 # Used by _run_check and _run_restart.
1217 #
1218 # The command is run via open3. Output from stdout and stderr is collected
1219 # until the command exits. It does not wait for the
1220 # pipes to close, as a daemon started by the command may keep them open.
1221 #
1222 # On timeout, if a signal is given, it is sent to the command, and to its
1223 # child processes first if kill_sub_pids is 1. Then the pipes are closed and
1224 # the command is given up on. Without a signal it is left running and if it
1225 # writes again it gets SIGPIPE, or whatever it does to handle the reader
1226 # going away. Either way its exit code is never collected.
1227 #
1228 # Args...
1229 #
1230 # - command :: The command to run, after variable substitution.
1231 #
1232 # - timeout :: Seconds to wait before giving up on it.
1233 #
1234 # - timeout_signal :: Signal name to send on timeout, without the SIG
1235 # prefix, such as 'TERM'. undef to send nothing.
1236 #
1237 # - kill_sub_pids :: 1 to also send the signal to all child processes
1238 # of the command. See _signal_sub_pids.
1239 #
1240 # Returns a hash ref as below.
1241 #
1242 # - output :: stdout and stderr, with the final newline removed. On
1243 # timeout, whatever came in before it.
1244 #
1245 # - exit :: The exit code. 128 plus the signal number if it died on a
1246 # signal. -1 if it timed out or could not be executed.
1247 #
1248 # - error :: Only present if it timed out, died on a signal, or could
1249 # not be executed. On timeout with a signal, says it was sent along
1250 # with any problems sending it.
1251 #
1252 # - wait_status :: The raw $? from waitpid, or undef if it timed out or
1253 # could not be executed.
1254 #
1255 # Example...
1256 #
1257 # my $result = $self->_run_command( '/usr/sbin/service apache24 restart', 30, undef, 1 );
1258 # # $result is { output => 'Performing sanity check...', exit => 0, wait_status => 0 }
1259 #
1260 # my $result = $self->_run_command( '/bin/sleep 60', 1, undef, 1 );
1261 # # $result is { output => '', exit => -1, error => 'timed out after 1 seconds' }
1262 #
1263 # my $result = $self->_run_command( '/bin/sleep 60', 1, 'TERM', 1 );
1264 # # $result is { output => '', exit => -1, error => 'timed out after 1 seconds, sent SIGTERM' }
1265 376 ▶sub _run_command {
Subroutine _run_command: called CC=23 SCAR=31.4
1266 376 my ( $self, $command, $timeout, $timeout_signal, $kill_sub_pids ) = @_;
1267  
1268 376 my %result = ( output => '', exit => -1 );
1269 376 my $wait_status;
1270 my @signal_errors;
1271 376 eval {
1272 376 my $pid = open3( my $std_in, my $std_out, my $std_err = gensym, $command );
1273 372 close($std_in);
1274  
1275 372 my $select = IO::Select->new( $std_out, $std_err );
1276 372 my $deadline = Time::HiRes::time + $timeout;
1277 372 ▶ while ( !defined($wait_status) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $wait_status) 9042 352 9394
1278 9042 my $remaining = $deadline - Time::HiRes::time;
1279 9042 ▶ if ( $remaining <= 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining <= 0) 20 9022 9042
1280 20 last;
1281 }
1282  
1283 # wake up at least every 0.1 seconds to see if it has exited
1284 9022 ▶ my $wait = $remaining < 0.1 ? $remaining : 0.1;
Branch: 1 branch
BranchTrueFalseTotal
$remaining < 0.1 ? : 20 9002 9022
1285 9022 ▶ if ( $select->count ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($select->count) { } 9002 20 9022
1286 9002 foreach my $handle ( $select->can_read($wait) ) {
1287 7515 ▶ if ( sysread( $handle, my $buffer, 4096 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (sysread $handle, my $buffer, 4096) { } 6817 698 7515
1288 6817 $result{output} = $result{output} . $buffer;
1289 } else {
1290 698 $select->remove($handle);
1291 }
1292 }
1293 } else {
1294 20 select( undef, undef, undef, $wait );
1295 }
1296  
1297 9022 ▶ if ( waitpid( $pid, WNOHANG ) == $pid ) {
Branch: 1 branch
BranchTrueFalseTotal
if (waitpid($pid, 1) == $pid) 352 8670 9022
1298 352 $wait_status = $?;
1299 }
1300 } ## end while ( !defined($wait_status) )
1301  
1302 # grab anything left that is ready now, without waiting on pipes held open by others
1303 372 ▶ if ( defined($wait_status) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $wait_status) 352 20 372
1304 352 my $drain_deadline = Time::HiRes::time + 1;
1305 352 ▶ while ( $select->count && Time::HiRes::time < $drain_deadline ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($select->count and &Time::HiRes::time() < $drain_deadline) 28688 350 29038
Condition100%3/3
$select->count and &Time::HiRes::time() < $drain_deadline
!ll&&!rl&&r
348228688
MC/DC100%2/2
$select->count and &Time::HiRes::time() < $drain_deadline
$select->count &Time::HiRes::time() < $drain_deadline
Truth table100%3/3
A and B
A= $select->countB= &Time::HiRes::time() < $drain_deadline
ABresult
0X0
100
111
1306 28688 my @ready = $select->can_read(0);
1307 28688 ▶ if ( !defined( $ready[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ready[0]) 2 28686 28688
1308 2 last;
1309 }
1310 28686 foreach my $handle (@ready) {
1311 28686 ▶ if ( sysread( $handle, my $buffer, 4096 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (sysread $handle, my $buffer, 4096) { } 28686 0 28686
1312 28686 $result{output} = $result{output} . $buffer;
1313 } else {
1314 0 $select->remove($handle);
1315 }
1316 }
1317 } ## end while ( $select->count && Time::HiRes::time < $drain_deadline )
1318 } ## end if ( defined($wait_status) )
1319  
1320 # children first, as once the command is gone they are no longer findable via its PID
1321 372 ▶ if ( !defined($wait_status) && defined($timeout_signal) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $wait_status and defined $timeout_signal) 8 364 372
Condition100%3/3
not defined $wait_status and defined $timeout_signal
!ll&&!rl&&r
352128
MC/DC100%2/2
not defined $wait_status and defined $timeout_signal
not defined $wait_status defined $timeout_signal
Truth table100%3/3
not(A) and B
A= not defined $wait_statusB= defined $timeout_signal
ABresult
0X0
100
111
1322 8 ▶ if ($kill_sub_pids) {
Branch: 1 branch
BranchTrueFalseTotal
if ($kill_sub_pids) 4 4 8
1323 4 push( @signal_errors, $self->_signal_sub_pids( $timeout_signal, $pid ) );
1324 }
1325 8 ▶ if ( !kill( $timeout_signal, $pid ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (kill $timeout_signal, $pid) 0 8 8
1326 0 push( @signal_errors, 'failed to send SIG' . $timeout_signal . ' to ' . $pid . ': ' . $! );
1327 }
1328 }
1329  
1330 372 close($std_out);
1331 372 close($std_err);
1332 };
1333 376 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 4 372 376
1334 4 $result{output} = $@;
1335 4 $result{error} = 'failed to execute';
1336 4 chomp( $result{output} );
1337 4 return \%result;
1338 }
1339  
1340 372 chomp( $result{output} );
1341 372 ▶ if ( !defined($wait_status) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $wait_status) { } 20 352 372
elsif ($wait_status & 127) { } 6 346 352
1342 20 $result{error} = 'timed out after ' . $timeout . ' seconds';
1343 20 ▶ if ( defined($timeout_signal) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $timeout_signal) 8 12 20
1344 8 $result{error} = $result{error} . ', sent SIG' . $timeout_signal;
1345 8 ▶ if ( defined( $signal_errors[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $signal_errors[0]) 0 8 8
1346 0 $result{error} = $result{error} . ', ' . join( '; ', @signal_errors );
1347 }
1348 }
1349 } elsif ( $wait_status & 127 ) {
1350 6 $result{wait_status} = $wait_status;
1351 6 $result{exit} = 128 + ( $wait_status & 127 );
1352 6 $result{error} = 'child died with signal ' . ( $wait_status & 127 );
1353 } else {
1354 346 $result{wait_status} = $wait_status;
1355 346 $result{exit} = $wait_status >> 8;
1356 }
1357  
1358 372 return \%result;
1359 } ## end sub _run_command
1360  
1361 # Runs a perl check, a command in the form 'perl:$name $args', in process
1362 # via Monitoring::Sneck::Checks, and returns the same as _run_command does,
1363 # so _run_check can handle both alike. Monitoring::Sneck::Checks is only
1364 # loaded the first time one is run, so it is only needed if used. Used by
1365 # _run_check.
1366 #
1367 # The args are handed over as is, for Getopt::Long to split. Unbalanced
1368 # quotes are UNKNOWN, a exit of 3. The check is given the timeout and is
1369 # also UNKNOWN if it runs past it.
1370 #
1371 # Args...
1372 #
1373 # - command :: The command, after variable substitution, such as
1374 # 'perl:http -H www.example.org -w 1 -c 2'.
1375 #
1376 # - timeout :: Seconds to give it.
1377 #
1378 # Returns a hash ref as below.
1379 #
1380 # - output :: The combined stdout and stderr of the check, with the
1381 # final newline removed.
1382 #
1383 # - exit :: The code the check returned, 0 to 3, or -1 if it, or
1384 # Monitoring::Sneck::Checks, could not be loaded.
1385 #
1386 # - error :: Only present for a exit of -1. Says why.
1387 #
1388 # - wait_status :: Always undef, as nothing was forked.
1389 #
1390 # Example...
1391 #
1392 # my $result = $self->_run_perl_check( 'perl:file_age -f /var/backups/db.sql.gz -w 90000 -c 180000', 30 );
1393 # # $result is { output => 'FILE_AGE OK - /var/backups/db.sql.gz is 3600 seconds old...', exit => 0, wait_status => undef }
1394 #
1395 # my $result = $self->_run_perl_check( 'perl:base', 30 );
1396 # # $result is { output => 'base is what checks are built on, not a check', exit => -1,
1397 # # error => 'failed to load perl check base', wait_status => undef }
1398 1 ▶sub _run_perl_check {
Subroutine _run_perl_check: called CC=3 SCAR=14.6
1399 1 my ( $self, $command, $timeout ) = @_;
1400  
1401 1 my %result = ( output => '', exit => -1, wait_status => undef );
1402 1 my ( $check_name, $arg_string ) = $command =~ /^perl:(\S*)\s*(.*)$/s;
1403  
1404 0 ▶ if ( !eval { require Monitoring::Sneck::Checks; 1 } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require Monitoring::Sneck::Checks; 1 } }) 1 0 1
1405 1 $result{output} = $@;
1406 1 $result{error} = 'failed to load Monitoring::Sneck::Checks';
1407 1 chomp( $result{output} );
1408 1 return \%result;
1409 }
1410  
1411 0 my $returned = Monitoring::Sneck::Checks->run( check => $check_name, args => $arg_string, timeout => $timeout );
1412 0 $result{output} = $returned->{combined};
1413 0 $result{exit} = $returned->{code};
1414 0 chomp( $result{output} );
1415 0 ▶ if ( $result{exit} == -1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result{"exit"} == -1) 0 0 0
1416 0 $result{error} = 'failed to load perl check ' . $check_name;
1417 }
1418  
1419 0 return \%result;
1420 } ## end sub _run_perl_check
1421  
1422 # Sends a signal to every process below a PID, deepest first, so a process
1423 # is signaled before its parent and is not orphaned out of reach. Children
1424 # are found via pgrep -P and signaled via pkill -P. Used on check and
1425 # restart timeouts.
1426 #
1427 # Args...
1428 #
1429 # - signal :: Signal name without the SIG prefix, such as 'TERM'.
1430 #
1431 # - pid :: The PID whose children, and their children, get the signal.
1432 # It is not signaled itself.
1433 #
1434 # Returns a array of problems, each a string, or a empty array if there
1435 # were none. pgrep or pkill finding nothing is not a problem.
1436 #
1437 # Example...
1438 #
1439 # my @errors = $self->_signal_sub_pids( 'TERM', 12345 );
1440 # # every process below 12345 got SIGTERM and @errors is ()
1441 #
1442 # my @errors = $self->_signal_sub_pids( 'TERM', 12345 );
1443 # # without pgrep installed, @errors is ( 'failed to run pgrep: No such file or directory' )
1444 12 ▶sub _signal_sub_pids {
Subroutine _signal_sub_pids: called CC=11 SCAR=27.2
1445 12 my ( $self, $signal, $pid ) = @_;
1446  
1447 12 my $pgrep_fh;
1448 12 ▶ if ( !open( $pgrep_fh, '-|', 'pgrep', '-P', $pid ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $pgrep_fh, "-|", "pgrep", "-P", $pid) 0 12 12
1449 0 return ( 'failed to run pgrep: ' . $! );
1450 }
1451 12 my @children;
1452 12 ▶ while ( my $line = <$pgrep_fh> ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $pgrep_fh)) 8 12 20
1453 8 ▶ if ( $line =~ /^([0-9]+)\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([0-9]+)\s*$/) 8 0 8
1454 8 push( @children, $1 );
1455 }
1456 }
1457 12 close($pgrep_fh);
1458 # 1 is nothing found
1459 12 ▶ if ( ( $? >> 8 ) > 1 || ( $? & 127 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($? >> 8 > 1 or $? & 127) 0 12 12
Condition33%1/3
$? >> 8 > 1 or $? & 127
l!l&&r!l&&!r
0012
MC/DC0%0/2
$? >> 8 > 1 or $? & 127
$? >> 8 > 1 $? & 127
Truth table33%1/3
A or B
A= $? >> 8 > 1B= $? & 127
ABresult
1X1
011
000
1460 0 return ( 'pgrep -P ' . $pid . ' failed with wait status ' . $? );
1461 }
1462  
1463 12 my @errors;
1464 12 foreach my $child (@children) {
1465 8 push( @errors, $self->_signal_sub_pids( $signal, $child ) );
1466 }
1467  
1468 12 ▶ if ( defined( $children[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $children[0]) 8 4 12
1469 8 system( 'pkill', '-' . $signal, '-P', $pid );
1470 8 ▶ if ( $? == -1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($? == -1) { } 0 8 8
elsif ($? >> 8 > 1 or $? & 127) { } 0 8 8
1471 0 push( @errors, 'failed to run pkill: ' . $! );
1472 ▶ } elsif ( ( $? >> 8 ) > 1 || ( $? & 127 ) ) {
Condition33%1/3
$? >> 8 > 1 or $? & 127
l!l&&r!l&&!r
008
MC/DC0%0/2
$? >> 8 > 1 or $? & 127
$? >> 8 > 1 $? & 127
Truth table33%1/3
A or B
A= $? >> 8 > 1B= $? & 127
ABresult
1X1
011
000
1473 0 push( @errors, 'pkill -' . $signal . ' -P ' . $pid . ' failed with wait status ' . $? );
1474 }
1475 }
1476  
1477 12 return @errors;
1478 } ## end sub _signal_sub_pids
1479  
1480  
1481 # Decides if a check result counts as failed for a restart. Critical
1482 # always does. Unknown and errored do if the restart does not ignore them.
1483 # Ok and warning never do.
1484 #
1485 # Args...
1486 #
1487 # - exit :: The exit code of the check, as stored in data.checks.
1488 #
1489 # - restart :: Hash ref of the restart as returned by the restarts
1490 # method of Monitoring::Sneck::Config.
1491 #
1492 # Returns 1 if failed, otherwise 0.
1493 #
1494 # Example...
1495 #
1496 # $self->_check_failed( 2, $restart ); # 1
1497 # $self->_check_failed( 3, { ignore_unknown => 1, ... } ); # 0
1498 # $self->_check_failed( 3, { ignore_unknown => 0, ... } ); # 1
1499 167 ▶sub _check_failed {
Subroutine _check_failed: called CC=8 SCAR=20.8
1500 167 my ( $self, $exit, $restart ) = @_;
1501  
1502 167 ▶ if ( !defined($exit) || $exit == 0 || $exit == 1 ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $exit or $exit == 0 or $exit == 1) { } 32 135 167
elsif ($exit == 2) { } 125 10 135
elsif ($exit == 3) { } 2 8 10
Condition83%5/6
not defined $exit or $exit == 0 or $exit == 1
l!l&&r!l&&!r
311135
not defined $exit or $exit == 0
l!l&&r!l&&!r
031136
MC/DC66%2/3
not defined $exit or $exit == 0 or $exit == 1
not defined $exit $exit == 0 $exit == 1
Truth table75%3/4
not(A) or B or C
A= not defined $exitB= $exit == 0C= $exit == 1
ABCresult
1XX1
01X1
0011
0000
1503 32 return 0;
1504 } elsif ( $exit == 2 ) {
1505 125 return 1;
1506 } elsif ( $exit == 3 ) {
1507 2 ▶ return $restart->{ignore_unknown} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$restart->{'ignore_unknown'} ? : 1 1 2
1508 }
1509 8 ▶ return $restart->{ignore_errored} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$restart->{'ignore_errored'} ? : 4 4 8
1510 } ## end sub _check_failed
1511  
1512 # Sorts restarts so every restart comes after the ones it depends on.
1513 # Restarts with nothing left to wait on are taken in name order. The
1514 # config has already been checked for cycles.
1515 #
1516 # Args...
1517 #
1518 # - restarts :: Hash ref as returned by the restarts method of
1519 # Monitoring::Sneck::Config.
1520 #
1521 # Returns a list of restart names.
1522 #
1523 # Example...
1524 #
1525 # # a_app depends on z_db
1526 # my @order = $self->_restart_order($restarts);
1527 # # @order is ( 'z_db', 'a_app' )
1528 98 ▶sub _restart_order {
Subroutine _restart_order: called CC=7 SCAR=19.5
1529 98 my ( $self, $restarts ) = @_;
1530  
1531 98 my %waiting_on;
1532 my %dependents;
1533 98 foreach my $name ( keys( %{$restarts} ) ) {
1534 147 $waiting_on{$name} = scalar( @{ $restarts->{$name}{depends} } );
1535 147 foreach my $depend ( @{ $restarts->{$name}{depends} } ) {
1536 35 push( @{ $dependents{$depend} }, $name );
1537 }
1538 }
1539  
1540 98 my @order;
1541 98 my @ready = sort( grep { $waiting_on{$_} == 0 } keys(%waiting_on) );
1542 98 ▶ while ( defined( $ready[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ready[0]) 147 98 245
1543 147 my $name = shift(@ready);
1544 147 push( @order, $name );
1545 147 ▶ foreach my $dependent ( @{ $dependents{$name} || [] } ) {
Condition100%2/2
$dependents{$name} || []
l!l
35112
MC/DC100%1/1
$dependents{$name} || []
$dependents{$name}
Truth table100%2/2
A
A= $dependents{$name}
Aresult
11
00
1546 35 $waiting_on{$dependent}--;
1547 35 ▶ if ( $waiting_on{$dependent} == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($waiting_on{$dependent} == 0) 33 2 35
1548 33 @ready = sort( @ready, $dependent );
1549 }
1550 }
1551 } ## end while ( defined( $ready[0] ) )
1552  
1553 98 return @order;
1554 } ## end sub _restart_order
1555  
1556 # Reads the restart state file. A missing file is a empty state and not a
1557 # error. A file that can not be read or parsed is also used as a empty
1558 # state, so restarts still happen, but a error is returned for
1559 # data.restart_state_error. Entries that are not in the expected form are
1560 # dropped.
1561 #
1562 # Returns a hash ref of restart names to hash refs of last_run, epoch
1563 # seconds of when it last finished, or when it last started if sneck died
1564 # while it was running, and attempts, threshold triggered runs
1565 # since its checks last recovered. Also returns a error string or undef.
1566 #
1567 # Example...
1568 #
1569 # my ( $state, $error ) = $self->_read_restart_state;
1570 # # $state is { httpd => { last_run => 1791491419, attempts => 2 } } and $error is undef
1571 98 ▶sub _read_restart_state {
Subroutine _read_restart_state: called CC=11 SCAR=24.0
1572 98 my $self = $_[0];
1573  
1574 98 my $file = $self->{state_file};
1575 98 ▶ if ( !-e $file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $file) 62 36 98
1576 62 return ( {}, undef );
1577 }
1578  
1579 36 my $decoded;
1580 36 eval {
1581 36 $decoded = JSON->new->decode( read_file($file) );
1582 };
1583 36 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 34 36
1584 2 my $error = $@;
1585 2 chomp($error);
1586 2 return ( {}, 'failed to read restart state file "' . $file . '"... ' . $error );
1587 }
1588 34 ▶ if ( ref($decoded) ne 'HASH' || ref( $decoded->{restarts} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded ne "HASH" or ref $decoded->{"restarts"} ne "HASH") 2 32 34
Condition100%3/3
ref $decoded ne "HASH" or ref $decoded->{"restarts"} ne "HASH"
l!l&&r!l&&!r
1132
MC/DC100%2/2
ref $decoded ne "HASH" or ref $decoded->{"restarts"} ne "HASH"
ref $decoded ne "HASH" ref $decoded->{"restarts"} ne "HASH"
Truth table100%3/3
A or B
A= ref $decoded ne "HASH"B= ref $decoded->{"restarts"} ne "HASH"
ABresult
1X1
011
000
1589 2 return ( {}, 'restart state file "' . $file . '" is not in the expected format' );
1590 }
1591  
1592 32 my %state;
1593 32 foreach my $name ( keys( %{ $decoded->{restarts} } ) ) {
1594 45 my $item = $decoded->{restarts}{$name};
1595 45 ▶ if ( ref($item) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item eq "HASH" and defined $item->{"last_run"} and $item->{"last_run"} =~ /^[0-9]+$/ and defined $item->{"attempts"} and $item->{"attempts"} =~ /^[0-9]+$/) 40 5 45
Condition100%12/12
ref $item eq "HASH" and defined $item->{"last_run"} and $item->{"last_run"} =~ /^[0-9]+$/ and defined $item->{"attempts"} and $item->{"attempts"} =~ /^[0-9]+$/
!ll&&!rl&&r
4140
ref $item eq "HASH" and defined $item->{"last_run"} and $item->{"last_run"} =~ /^[0-9]+$/ and defined $item->{"attempts"}
!ll&&!rl&&r
3141
ref $item eq "HASH" and defined $item->{"last_run"} and $item->{"last_run"} =~ /^[0-9]+$/
!ll&&!rl&&r
2142
ref $item eq "HASH" and defined $item->{"last_run"}
!ll&&!rl&&r
1143
MC/DC100%5/5
ref $item eq "HASH" and defined $item->{"last_run"} and $item->{"last_run"} =~ /^[0-9]+$/ and defined $item->{"attempts"} and $item->{"attempts"} =~ /^[0-9]+$/
ref $item eq "HASH" defined $item->{"last_run"} $item->{"last_run"} =~ /^[0-9]+$/ defined $item->{"attempts"} $item->{"attempts"} =~ /^[0-9]+$/
Truth table100%6/6
A and B and C and D and E
A= ref $item eq "HASH"B= defined $item->{"last_run"}C= $item->{"last_run"} =~ /^[0-9]+$/D= defined $item->{"attempts"}E= $item->{"attempts"} =~ /^[0-9]+$/
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
1596 && defined( $item->{last_run} )
1597 && $item->{last_run} =~ /^[0-9]+$/
1598 && defined( $item->{attempts} )
1599 && $item->{attempts} =~ /^[0-9]+$/ )
1600 {
1601 40 $state{$name} = { last_run => $item->{last_run} + 0, attempts => $item->{attempts} + 0 };
1602 }
1603 } ## end foreach my $name ( keys( %{ $decoded->{restarts} } ) )
1604  
1605 32 return ( \%state, undef );
1606 } ## end sub _read_restart_state
1607  
1608 # Writes the restart state file. It is written atomically via File::Slurp,
1609 # so a crash never leaves a half written file.
1610 #
1611 # Args...
1612 #
1613 # - state :: Hash ref as returned by _read_restart_state.
1614 #
1615 # Returns undef on success or a error string.
1616 #
1617 # Example...
1618 #
1619 # my $error = $self->_write_restart_state( { httpd => { last_run => 1791491419, attempts => 1 } } );
1620 # # writes {"restarts":{"httpd":{"attempts":1,"last_run":1791491419}}}
1621 205 ▶sub _write_restart_state {
Subroutine _write_restart_state: called CC=2 SCAR=6.9
1622 205 my ( $self, $state ) = @_;
1623  
1624 205 my $file = $self->{state_file};
1625 205 eval { write_file( $file, { atomic => 1 }, JSON->new->canonical(1)->encode( { restarts => $state } ) . "\n" ); };
1626 205 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 4 201 205
1627 4 my $error = $@;
1628 4 chomp($error);
1629 4 return 'failed to write restart state file "' . $file . '"... ' . $error;
1630 }
1631  
1632 201 return undef;
1633 } ## end sub _write_restart_state
1634  
1635 # Reads the compliance state file. A missing file is a empty state and not a
1636 # error. A file that can not be read or parsed is also used as a empty
1637 # state, so everything is just run, but a error is returned for
1638 # data.compliance_state_error. Entries that are not in the expected form
1639 # are dropped.
1640 #
1641 # Returns a hash ref of compliance check names to hash refs of last_ran,
1642 # epoch seconds of when it last started, and result, a hash ref of ran,
1643 # output, exit, run_time, and error if any, as stored in data.compliance.
1644 # Also returns a error string or undef.
1645 #
1646 # Example...
1647 #
1648 # my ( $state, $error ) = $self->_read_compliance_state;
1649 # # $state is { pkg_vulns => { last_ran => 1791491419, result => { ran => '...', output => '...',
1650 # # exit => 0, run_time => '1.234567890' } } } and $error is undef
1651 8 ▶sub _read_compliance_state {
Subroutine _read_compliance_state: called CC=21 SCAR=38.3
1652 8 my $self = $_[0];
1653  
1654 8 my $file = $self->{compliance_state_file};
1655 8 ▶ if ( !-e $file ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-e $file) 2 6 8
1656 2 return ( {}, undef );
1657 }
1658  
1659 6 my $decoded;
1660 6 eval {
1661 6 $decoded = JSON->new->decode( read_file($file) );
1662 };
1663 6 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 5 6
1664 1 my $error = $@;
1665 1 chomp($error);
1666 1 return ( {}, 'failed to read compliance state file "' . $file . '"... ' . $error );
1667 }
1668 5 ▶ if ( ref($decoded) ne 'HASH' || ref( $decoded->{compliance} ) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $decoded ne "HASH" or ref $decoded->{"compliance"} ne "HASH") 0 5 5
Condition33%1/3
ref $decoded ne "HASH" or ref $decoded->{"compliance"} ne "HASH"
l!l&&r!l&&!r
005
MC/DC0%0/2
ref $decoded ne "HASH" or ref $decoded->{"compliance"} ne "HASH"
ref $decoded ne "HASH" ref $decoded->{"compliance"} ne "HASH"
Truth table33%1/3
A or B
A= ref $decoded ne "HASH"B= ref $decoded->{"compliance"} ne "HASH"
ABresult
1X1
011
000
1669 0 return ( {}, 'compliance state file "' . $file . '" is not in the expected format' );
1670 }
1671  
1672 5 my %state;
1673 5 foreach my $name ( keys( %{ $decoded->{compliance} } ) ) {
1674 5 my $item = $decoded->{compliance}{$name};
1675 5 ▶ if ( ref($item) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"} and not ref $item->{"result"}{"output"} and defined $item->{"result"}{"exit"} and not ref $item->{"result"}{"exit"} and $item->{"result"}{"exit"} =~ /^-?[0-9]+$/) 5 0 5
Condition33%11/33
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"} and not ref $item->{"result"}{"output"} and defined $item->{"result"}{"exit"} and not ref $item->{"result"}{"exit"} and $item->{"result"}{"exit"} =~ /^-?[0-9]+$/
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"} and not ref $item->{"result"}{"output"} and defined $item->{"result"}{"exit"} and not ref $item->{"result"}{"exit"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"} and not ref $item->{"result"}{"output"} and defined $item->{"result"}{"exit"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"} and not ref $item->{"result"}{"output"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH"
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"}
!ll&&!rl&&r
005
ref $item eq "HASH" and defined $item->{"last_ran"}
!ll&&!rl&&r
005
MC/DC0%0/12
ref $item eq "HASH" and defined $item->{"last_ran"} and not ref $item->{"last_ran"} and $item->{"last_ran"} =~ /^[0-9]+$/ and ref $item->{"result"} eq "HASH" and defined $item->{"result"}{"ran"} and not ref $item->{"result"}{"ran"} and defined $item->{"result"}{"output"} and not ref $item->{"result"}{"output"} and defined $item->{"result"}{"exit"} and not ref $item->{"result"}{"exit"} and $item->{"result"}{"exit"} =~ /^-?[0-9]+$/
ref $item eq "HASH" defined $item->{"last_ran"} not ref $item->{"last_ran"} $item->{"last_ran"} =~ /^[0-9]+$/ ref $item->{"result"} eq "HASH" defined $item->{"result"}{"ran"} not ref $item->{"result"}{"ran"} defined $item->{"result"}{"output"} not ref $item->{"result"}{"output"} defined $item->{"result"}{"exit"} not ref $item->{"result"}{"exit"} $item->{"result"}{"exit"} =~ /^-?[0-9]+$/
Truth table7%1/13
A and B and not(C) and D and E and F and not(G) and H and not(I) and J and not(K) and L
A= ref $item eq "HASH"B= defined $item->{"last_ran"}C= not ref $item->{"last_ran"}D= $item->{"last_ran"} =~ /^[0-9]+$/E= ref $item->{"result"} eq "HASH"F= defined $item->{"result"}{"ran"}G= not ref $item->{"result"}{"ran"}H= defined $item->{"result"}{"output"}I= not ref $item->{"result"}{"output"}J= defined $item->{"result"}{"exit"}K= not ref $item->{"result"}{"exit"}L= $item->{"result"}{"exit"} =~ /^-?[0-9]+$/
ABCDEFGHIJKLresult
0XXXXXXXXXXX0
10XXXXXXXXXX0
110XXXXXXXXX0
1110XXXXXXXX0
11110XXXXXXX0
111110XXXXXX0
1111110XXXXX0
11111110XXXX0
111111110XXX0
1111111110XX0
11111111110X0
1111111111100
1111111111111
1676 && defined( $item->{last_ran} )
1677 && !ref( $item->{last_ran} )
1678 && $item->{last_ran} =~ /^[0-9]+$/
1679 && ref( $item->{result} ) eq 'HASH'
1680 && defined( $item->{result}{ran} )
1681 && !ref( $item->{result}{ran} )
1682 && defined( $item->{result}{output} )
1683 && !ref( $item->{result}{output} )
1684 && defined( $item->{result}{exit} )
1685 && !ref( $item->{result}{exit} )
1686 && $item->{result}{exit} =~ /^-?[0-9]+$/ )
1687 {
1688 5 my %result = ( ran => $item->{result}{ran}, output => $item->{result}{output}, exit => $item->{result}{exit} + 0 );
1689 5 foreach my $key ( 'error', 'run_time' ) {
1690 10 ▶ if ( defined( $item->{result}{$key} ) && !ref( $item->{result}{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $item->{"result"}{$key} and not ref $item->{"result"}{$key}) 5 5 10
Condition66%2/3
defined $item->{"result"}{$key} and not ref $item->{"result"}{$key}
!ll&&!rl&&r
505
MC/DC50%1/2
defined $item->{"result"}{$key} and not ref $item->{"result"}{$key}
defined $item->{"result"}{$key} not ref $item->{"result"}{$key}
Truth table66%2/3
A and not(B)
A= defined $item->{"result"}{$key}B= not ref $item->{"result"}{$key}
ABresult
0X0
100
111
1691 5 $result{$key} = $item->{result}{$key};
1692 }
1693 }
1694 5 $state{$name} = { last_ran => $item->{last_ran} + 0, result => \%result };
1695 } ## end if ( ref($item) eq 'HASH' && defined( $item->{last_ran} ) ...)
1696 } ## end foreach my $name ( keys( %{ $decoded->{compliance} } ) )
1697  
1698 5 return ( \%state, undef );
1699 } ## end sub _read_compliance_state
1700  
1701 # Writes the compliance state file. It is written atomically via
1702 # File::Slurp, so a crash never leaves a half written file.
1703 #
1704 # Args...
1705 #
1706 # - state :: Hash ref as returned by _read_compliance_state.
1707 #
1708 # Returns undef on success or a error string.
1709 #
1710 # Example...
1711 #
1712 # my $error = $self->_write_compliance_state( { pkg_vulns => { last_ran => 1791491419,
1713 # result => { ran => '...', output => '...', exit => 0, run_time => '1.234567890' } } } );
1714 # # writes {"compliance":{"pkg_vulns":{"last_ran":1791491419,"result":{...}}}}
1715 8 ▶sub _write_compliance_state {
Subroutine _write_compliance_state: called CC=2 SCAR=6.9
1716 8 my ( $self, $state ) = @_;
1717  
1718 8 my $file = $self->{compliance_state_file};
1719 8 eval {
1720 8 write_file( $file, { atomic => 1 }, JSON->new->canonical(1)->encode( { compliance => $state } ) . "\n" );
1721 };
1722 8 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 7 8
1723 1 my $error = $@;
1724 1 chomp($error);
1725 1 return 'failed to write compliance state file "' . $file . '"... ' . $error;
1726 }
1727  
1728 7 return undef;
1729 } ## end sub _write_compliance_state
1730  
1731 =head1 AUTHOR
1732  
1733 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.net> >>
1734  
1735 =head1 BUGS
1736  
1737 Please report any bugs or feature requests to C<bug-monitoring-sneck at rt.cpan.org>, or through
1738 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Monitoring-Sneck>. I will be notified, and then you'll
1739 automatically be notified of progress on your bug as I make changes.
1740  
1741 =head1 SUPPORT
1742  
1743 You can find documentation for this module with the perldoc command.
1744  
1745 perldoc Monitoring::Sneck
1746  
1747 You can also look for information at:
1748  
1749 =over 4
1750  
1751 =item * RT: CPAN's request tracker (report bugs here)
1752  
1753 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Monitoring-Sneck>
1754  
1755 =item * Search CPAN
1756  
1757 L<https://metacpan.org/release/Monitoring-Sneck>
1758  
1759 =item * Github
1760  
1761 L<https://github.com/VVelox/Monitoring-Sneck>
1762  
1763 =back
1764  
1765 =head1 LICENSE AND COPYRIGHT
1766  
1767 This software is Copyright (c) 2023 by Zane C. Bowers-Hadley.
1768  
1769 This is free software, licensed under:
1770  
1771 The Artistic License 2.0 (GPL Compatible)
1772  
1773 =cut
1774  
1775 59 1; # End of Monitoring::Sneck
↑ Summary blib/lib/Monitoring/Sneck/Config.pm »