blib/lib/Monitoring/Sneck/Config.pm

filter: Statementstmt 99.3% 577 / 581 Branchbran 98.9% 271 / 274 Conditioncond 84.8% 112 / 132 MC/DCmcdc 76.3% 55 / 72 Subroutinesub 100% 41 / 41 Podpod 100% 16 / 16 totaltotal 96.0% 1072 / 1116 CC 204 SCAR 28.7
CC
204
Cov
97%
_add_restart
39.0
_add_compliance
28.5
_parse_yaml
23.0
CRAP 17.6
« blib/lib/Monitoring/Sneck.pm ↑ Summary /usr/local/bin/perldoc »
1 package Monitoring::Sneck::Config;
2  
3 60 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 60 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 60 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 60 ▶use File::Slurp qw(read_file);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 60 ▶use Config qw(%Config);
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 =head1 NAME
10  
11 Monitoring::Sneck::Config - parses and validates sneck config files
12  
13 =head1 VERSION
14  
15 Version 1.7.0
16  
17 =cut
18  
19 60 our $VERSION = '1.7.0';
20  
21 =head1 SYNOPSIS
22  
23 use Monitoring::Sneck::Config;
24  
25 my $config;
26 eval { $config = Monitoring::Sneck::Config->new( { file => '/usr/local/etc/sneck.conf' } ); };
27 if ($@) {
28 die($@);
29 }
30  
31 if ( !$config->is_valid ) {
32 foreach my $error ( $config->errors ) {
33 print $error->{where} . ': ' . $error->{message} . "\n";
34 }
35 }
36  
37 foreach my $name ( sort keys %{ $config->checks } ) {
38 print $name . ' runs ' . $config->substitute( $config->checks->{$name} ) . "\n";
39 }
40  
41 =head1 CONFIG FORMAT
42  
43 Two formats are supported, the sneck format and YAML. Files ending in
44 .yaml or .yml are read as YAML, anything else as the sneck format. This
45 can be overridden via the format arg to new.
46  
47 The following applies to both.
48  
49 Names of options, variables, environment variables, checks, debug
50 checks, compliance checks, and restarts are made up of A-Z, a-z, 0-9,
51 and _.
52  
53 Variables are used in commands in the form /%+variable_name%+/. A
54 reference to a variable that is not defined is left as written and
55 produces a warning, as it may just be part of the command, such as
56 'date +%Y%m%d'.
57  
58 Debug checks are the same as checks, but are not counted towards any of
59 the counts. They exist purely for debugging. A check and a debug check
60 may share a name.
61  
62 Compliance checks are checks for how a system is set up, such as sshd
63 settings or file modes, rather than if something is working. They are
64 counted separately from checks and do not set alert by default. A
65 compliance check may share a name with a check or debug check. See
66 COMPLIANCE.
67  
68 Commands may not be empty.
69  
70 Checks, debug checks, and compliance checks starting with perl: are
71 perl checks, run in process. See PERL CHECKS.
72  
73 Environment variables are only set if the whole config is valid.
74  
75 =head2 SNECK FORMAT
76  
77 Each line has leading spaces and tabs removed before it is looked at. A
78 trailing \r is also removed, so files with CRLF line endings work.
79  
80 Blank lines are ignored.
81  
82 Lines starting with # are comments and are ignored.
83  
84 Lines matching /^[Ee][Nn][Vv]\ [A-Za-z0-9\_]+\=/ set environment
85 variables. The name is between the space and the first =, the value is
86 everything after it. The value may be empty. These may be set more than
87 once, with the last one winning.
88  
89 Lines matching /^\$[A-Za-z0-9\_]+\=/ are options. The name is between
90 the $ and the first =, the value is everything after it. See OPTIONS.
91  
92 Lines matching /^[A-Za-z0-9\_]+\=/ are variables. The name is before the
93 first =, the value is everything after it. The value may be empty.
94  
95 Lines matching /^[A-Za-z0-9\_]+\|/ are checks. The name is before the
96 first |, the command is everything after it with leading whitespace
97 removed.
98  
99 Lines matching /^\%[A-Za-z0-9\_]+\|/ are debug checks. The leading % is
100 not part of the name.
101  
102 Lines matching /^\@[A-Za-z0-9\_]+\|[^\|]*\|/ are restarts. The name is
103 between the @ and the first |, the options are between the first and
104 second |, and the command is everything after the second |, with
105 leading whitespace removed. Options are separated by spaces or tabs and
106 are in the form key=value. Values containing spaces or tabs may be
107 quoted with " or ', such as not_every="* 0-3 * * *". The checks and
108 depends options are comma separated lists. See RESTARTS.
109  
110 Lines matching /^\![A-Za-z0-9\_]+\|[^\|]*\|/ are compliance checks. They
111 are laid out the same as restarts, with the name after the !. The
112 options may be empty, but the second | is still needed, such as
113 !foo||/bin/true. See COMPLIANCE.
114  
115 Any other sort of line is an error.
116  
117 Option, variable, check, debug check, compliance check, and restart
118 names may not be redefined.
119  
120 =head3 EXAMPLE SNECK CONFIG
121  
122 env PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
123 # this is a comment
124 GEOM_DEV=foo
125 geom_foo|/usr/local/libexec/nagios/check_geom mirror %GEOM_DEV%
126 does_not_exist|/bin/this_will_error yup... that it will
127  
128 does_not_exist_2|/usr/bin/env /bin/this_will_also_error
129  
130 #includes route info
131 %routes|netstat -rn
132  
133 php_check|/usr/local/libexec/nagios/check_procs -C php-fpm -c 1:
134 @php_fpm|checks=php_check|/usr/sbin/service php_fpm restart
135  
136 The first line sets the environment variable PATH.
137  
138 The second is ignored as it is a comment.
139  
140 The third sets the variable GEOM_DEV to 'foo'.
141  
142 The fourth creates a check named geom_foo that calls check_geom with
143 the value of the variable GEOM_DEV.
144  
145 The fifth is an example of a check that calls a file that does not
146 exist.
147  
148 The sixth line is ignored as it is blank.
149  
150 The seventh is an example of another command erroring.
151  
152 The eighth is ignored as it is blank.
153  
154 The ninth is ignored as it is a comment.
155  
156 The tenth creates a debug check named routes.
157  
158 The eleventh is ignored as it is blank.
159  
160 The twelfth creates a check named php_check.
161  
162 The thirteenth creates a restart named php_fpm that runs the command
163 when php_check is critical, if restarts are enabled.
164  
165 When it is run, errors for the fifth and seventh lines are printed to
166 STDERR. For this reason, use '2> /dev/null' when calling it from snmpd
167 or '2> /dev/null > /dev/null' when calling it from cron.
168  
169 =head2 YAML FORMAT
170  
171 This needs L<YAML::XS>, which is optional and only loaded when a YAML
172 config is used.
173  
174 The top level is a mapping with up to seven keys, each of which is a
175 mapping of names to values.
176  
177 - options :: Options. See OPTIONS.
178  
179 - env :: Environment variables to set. Set in sorted name order.
180  
181 - vars :: Variables.
182  
183 - checks :: Checks, with the command as the value.
184  
185 - debugs :: Debug checks, with the command as the value.
186  
187 - compliance :: Compliance checks. Each is a mapping of options plus
188 command. See COMPLIANCE.
189  
190 - restarts :: Restarts. Each is a mapping of options plus command.
191 See RESTARTS.
192  
193 Any other top level key is an error. Any section may be left out or
194 empty. An empty file is a valid config with nothing in it.
195  
196 Values must be strings or numbers. An empty value, such as 'FOO:' or
197 'FOO: ~', is an empty string for env and vars and an error for checks
198 and debugs.
199  
200 YAML::XS turns some unquoted values into something else. 'true' becomes
201 1 and 'false' becomes a empty string. Quote values like those.
202  
203 Values starting with % or containing ': ' or ending in ':' must be quoted,
204 such as '-w 80 -c 1:'.
205  
206 YAML::XS keeps the last of any duplicate keys without saying anything,
207 so redefinitions can not be caught like they are in the sneck format.
208  
209 =head3 EXAMPLE YAML CONFIG
210  
211 env:
212 PATH: /sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
213 vars:
214 GEOM_DEV: foo
215 checks:
216 geom_foo: /usr/local/libexec/nagios/check_geom mirror %GEOM_DEV%
217 does_not_exist: /bin/this_will_error yup... that it will
218 php_check: '/usr/local/libexec/nagios/check_procs -C php-fpm -c 1:'
219 debugs:
220 routes: netstat -rn
221 restarts:
222 php_fpm:
223 command: /usr/sbin/service php_fpm restart
224 checks: [php_check]
225  
226 =head1 OPTIONS
227  
228 Options are settings for sneck itself. Options given on the command
229 line override these. cache_file, pid_dir, and locking are only used by
230 sneck, not L<Monitoring::Sneck>.
231  
232 - cache_file :: The cache file. The same as B<-C> for sneck.
233 May not be empty.
234  
235 - pid_dir :: The directory for the PID file used for locking. The
236 same as B<-P> for sneck. May not be empty.
237  
238 - locking :: If 1, locking is enabled. The same as B<-l> for sneck.
239 B<-L> disables it. Takes true and false in YAML.
240  
241 - check_timeout :: Seconds to wait on each check, debug check, and
242 compliance check before giving up on it. Compliance checks may
243 override it via their timeout option. Works the same as timeout for restarts.
244 A timeout counts as errored, with a exit of -1. The same as B<-T>
245 for sneck.
246 Default :: 30
247  
248 - check_timeout_signal :: Signal to send a check, debug check, or
249 compliance check on timeout. Works the same as timeout_signal for restarts. The same
250 as B<-s> for sneck.
251 Default :: none
252  
253 - check_kill_sub_pids :: If 1, the timeout signal is also sent to
254 all child processes of the check, debug check, or compliance
255 check. Works the same
256 as kill_sub_pids for restarts. The same as B<-k> for sneck. B<-K>
257 disables it. Takes true and false in YAML.
258 Default :: 1
259  
260 - compliance_alert :: If 1, compliance checks that are not ok and not
261 waived also set alert and are added to alertString, the same as
262 checks. Takes true and false in YAML.
263 Default :: 0
264  
265 Any other option is an error.
266  
267 $cache_file=/var/db/sneck/sneck.cache
268 $pid_dir=/var/run/sneck
269 $locking=1
270 $check_timeout=60
271 $check_timeout_signal=TERM
272  
273 options:
274 cache_file: /var/db/sneck/sneck.cache
275 pid_dir: /var/run/sneck
276 locking: true
277 check_timeout: 60
278 check_timeout_signal: TERM
279  
280 =head1 COMPLIANCE
281  
282 A compliance check is a nagios style check for how a system is set up,
283 such as root logins being off or a file having the right mode. They are
284 run the same as checks, but are counted separately, under
285 compliance_ok, compliance_critical, and the like, and set
286 compliance_alert instead of alert. Set the compliance_alert option to
287 also have them set alert.
288  
289 Restarts can not watch compliance checks.
290  
291 Options are as below. All are optional.
292  
293 - control :: The ID of the control it checks, such as CIS-5.2.10.
294 Used in place of the name in compliance_alertString.
295 Default :: none
296  
297 - framework :: The framework the control is from, such as CIS or
298 STIG. Compliance checks with a framework also get counts and a
299 score for it under compliance_frameworks.
300 Default :: none
301  
302 - severity :: One of low, medium, high, or critical, in any case.
303 Only used for reporting. It does not change how the exit code is
304 counted.
305 Default :: none
306  
307 - interval :: Minimum seconds between runs. Until it is due again,
308 the last result is reused and marked as cached. A change to the
309 command, after variables are put in place, makes it run right
310 away. 0 runs it every time.
311 Default :: 0
312  
313 - timeout :: Seconds to wait on it before giving up on it. Works
314 the same as check_timeout, which is used if this is not set.
315 Default :: check_timeout
316  
317 - waived_until :: A date in the form YYYY-MM-DD. Through the end of
318 that day, local time, a warning, critical, or unknown result is
319 counted as waived instead. Errored is never waived, as that means
320 the check itself is broken. Once the date passes, it counts as
321 normal again.
322 Default :: none
323  
324 - waiver :: Why it is waived, such as a ticket number. Needs
325 waived_until.
326 Default :: none
327  
328 The state used for interval is kept in a file. For sneck, this is the
329 cache file name with '.compliance' added, so by default
330 /var/cache/sneck.cache.compliance.
331  
332 !ssh_no_root|control=CIS-5.2.10 framework=CIS severity=high|sshd -T | grep -qi '^permitrootlogin no$'
333 !pkg_vulns|control=VULN-1 severity=high interval=86400 timeout=300|/usr/local/libexec/nagios/check_pkg_audit
334 !telnet_off|control=CIS-2.2.18 framework=CIS waived_until=2026-12-31 waiver="legacy box, ticket 1234"|/usr/local/libexec/sneck/check_telnet_off
335  
336 compliance:
337 ssh_no_root:
338 command: sshd -T | grep -qi '^permitrootlogin no$'
339 control: CIS-5.2.10
340 framework: CIS
341 severity: high
342 pkg_vulns:
343 command: /usr/local/libexec/nagios/check_pkg_audit
344 control: VULN-1
345 severity: high
346 interval: 86400
347 timeout: 300
348 telnet_off:
349 command: /usr/local/libexec/sneck/check_telnet_off
350 control: CIS-2.2.18
351 framework: CIS
352 waived_until: 2026-12-31
353 waiver: legacy box, ticket 1234
354  
355 =head1 PERL CHECKS
356  
357 A check, debug check, or compliance check in the form
358 'perl:$name $args' runs the check $name from L<Monitoring::Sneck::Checks>
359 inside of sneck, instead of starting a program for it. Each is a
360 module, such as L<Monitoring::Sneck::Checks::http>, whose POD lists its
361 args.
362  
363 www|perl:http -H www.example.org -S -w 1 -c 2
364 www_cert|perl:https_cert -H www.example.org -w 30 -c 14
365 !hosts_file|control=LOCAL-1|perl:hosts -e db.example.org=%DB_IP%
366  
367 Variables are put in place first, then the args are split as a shell
368 would, so quote args with spaces in them.
369  
370 The name must be a-z, 0-9, and _, starting with a letter, which is
371 checked along with the args having balanced quotes when the config is
372 read. Whether the check is there is only known when it is run.
373  
374 The exit is what the check returns, as for any other command, with two
375 differences. A exit of -1, which is errored, means the check, or
376 Monitoring::Sneck::Checks, could not be loaded, such as it not being
377 installed or the name being base. Running past check_timeout, or the
378 timeout of a compliance check, is UNKNOWN, a exit of 3, as nothing is
379 forked to be killed. Each check passes the timeout on to what it talks
380 to the network through, so this is rare. check_timeout_signal and
381 check_kill_sub_pids do not apply.
382  
383 Monitoring::Sneck::Checks is optional and only loaded once a perl check
384 is run.
385  
386 Restarts can not be perl checks, as they are commands to run, not
387 checks. A restart command starting with perl: is a error. Restarts may
388 watch perl checks though, and check_restart reruns them in process.
389  
390 =head1 RESTARTS
391  
392 A restart is a command that is run when enough of the checks it watches
393 fail. Restarts only run when asked for, via the restart option of
394 L<Monitoring::Sneck> or B<-r> for sneck. Otherwise they are just
395 reported.
396  
397 The command can not be a perl check. See PERL CHECKS.
398  
399 Options are as below.
400  
401 - checks :: Required. The checks to watch. Debug checks and
402 compliance checks can not be watched.
403  
404 - threshold :: How many of the watched checks must fail for it to
405 trigger. Must be between 1 and the number of checks.
406 Default :: 1
407  
408 - depends :: Other restarts this one depends on. When both trigger,
409 the ones depended on run first. A depend that did not trigger is
410 assumed to be fine and is not run. If a depend runs and fails,
411 or was itself skipped for that reason, this one is skipped.
412 Dependency cycles are errors.
413 Default :: none
414  
415 - cascade :: If 1, this also runs when any of its depends ran
416 without failing, even if its own threshold was not met.
417 Default :: 0
418  
419 - ignore_unknown :: If 0, unknown, exit 3, counts as failed.
420 Default :: 1
421  
422 - ignore_errored :: If 0, errored counts as failed. This is any
423 exit other than 0 to 3, dying on a signal, or not being able to
424 run the check.
425 Default :: 1
426  
427 - min_interval :: Minimum seconds from when this restart last
428 finished to when it may run again. 0 turns it off.
429 Default :: 180
430  
431 - max_retries :: How many times in a row it will run for its
432 threshold before giving up until its checks recover. 0 means
433 always retry. Runs from cascade do not count towards this.
434 Default :: 0
435  
436 - timeout :: Seconds to wait on the command before giving up on it.
437 On timeout its output pipes are closed and it is left running,
438 unless timeout_signal is set. If it writes again it gets SIGPIPE,
439 or whatever it does when the reader goes away. A timeout counts
440 as failed, with a exit of -1.
441 Default :: 30
442  
443 - timeout_signal :: Signal to send the command on timeout, as a
444 name such as TERM or SIGTERM, or a number. 0 is not allowed. It is
445 sent to the PID of the command and it is not waited on afterwards.
446 If the command has shell metacharacters in it, that PID is the
447 /bin/sh running it, so use kill_sub_pids to reach the command.
448 Default :: none
449  
450 - kill_sub_pids :: If 1, the timeout signal is also sent to all
451 child processes of the command, found via pgrep and signaled via
452 pkill, deepest first. Does nothing without timeout_signal.
453 Default :: 1
454  
455 - check_restart :: If 1, its checks are rerun after the command
456 finishes and their results replace the earlier ones in what is
457 returned. If they still meet the threshold, the restart counts
458 as failed, the same as the command failing.
459 Default :: 0
460  
461 - check_restart_delay :: Seconds to wait after the command finishes
462 before rerunning its checks. Does nothing without check_restart.
463 Default :: 5
464  
465 - not_every :: A maintenance window, as a five field cron spec of
466 minute, hour, day of month, month, and day of week. While the
467 local time matches it, this restart does not run. Only numbers
468 are allowed, no names such as sat or jan. Sunday is 0 or 7. As
469 with cron, if both day of month and day of week are given, either
470 one matching is enough. Restarts depending on one held back by
471 this treat it as if it did not trigger. In the sneck format it
472 must be quoted. In YAML it must be quoted if it starts with *.
473 Matched via L<DateTime::Event::Cron>.
474 Default :: none
475  
476 Critical always counts as failed. Ok and warning never do.
477  
478 The 0/1 options also take true and false in YAML.
479  
480 Restart commands get variables put in place the same as checks. A
481 restart does not wait for its output to be closed once its command has
482 exited, so a daemon started by it holding stdout open is fine.
483  
484 The command is also given the environment variables below, describing
485 why it is running.
486  
487 - SNECK_RESTART :: The name of the restart.
488  
489 - SNECK_REASON :: Either 'threshold' or 'cascade'.
490  
491 - SNECK_CASCADE_FROM :: The depend it cascaded from, or empty.
492  
493 - SNECK_FAILED_CHECKS :: Comma separated list of its checks that
494 counted as failed. May be empty for a cascade.
495  
496 - SNECK_CHECKS :: Comma separated list of the checks it watches.
497  
498 - SNECK_THRESHOLD :: The threshold.
499  
500 - SNECK_ATTEMPTS :: Runs for its threshold since its checks last
501 recovered, this one included.
502  
503 @httpd|checks=http_check,php_check threshold=2 depends=php_fpm cascade=1 timeout=60|/usr/sbin/service apache24 restart
504  
505 restarts:
506 httpd:
507 command: /usr/sbin/service apache24 restart
508 checks: [http_check, php_check]
509 threshold: 2
510 depends: [php_fpm]
511 cascade: true
512 timeout: 60
513  
514 @php_fpm|checks=php_check timeout=60 timeout_signal=TERM check_restart=1|/usr/sbin/service php_fpm restart
515  
516 restarts:
517 php_fpm:
518 command: /usr/sbin/service php_fpm restart
519 checks: [php_check]
520 timeout: 60
521 timeout_signal: TERM
522 check_restart: true
523  
524 @php_fpm|checks=php_check not_every="* 2-3 * * 0"|/usr/sbin/service php_fpm restart
525  
526 restarts:
527 php_fpm:
528 command: /usr/sbin/service php_fpm restart
529 checks: [php_check]
530 not_every: '* 2-3 * * 0'
531  
532 The last two never restart between 02:00 and 03:59 on Sundays.
533  
534 =head1 METHODS
535  
536 =head2 new
537  
538 Reads and parses a config.
539  
540 One argument is taken and that is a hash ref.
541  
542 - file :: Path to the config file to read.
543  
544 - raw :: The config as a string. Used instead of file if both
545 are given.
546  
547 - format :: Either 'sneck' or 'yaml'. If not given, a file ending
548 in .yaml or .yml, in any case, is 'yaml' and anything else,
549 including raw, is 'sneck'.
550  
551 Dies if neither file nor raw is given, the file can not be read, the
552 format is unknown, or the format is 'yaml' and YAML::XS can not be
553 loaded. Problems with the config itself never die. Check them via
554 is_valid and errors.
555  
556 my $config;
557 eval { $config = Monitoring::Sneck::Config->new( { file => $file } ); };
558 if ($@) {
559 die($@);
560 }
561  
562 my $config = Monitoring::Sneck::Config->new( { raw => "FOO=bar\nfoo_check|/bin/echo %FOO%\n" } );
563  
564 my $config = Monitoring::Sneck::Config->new( { raw => "checks:\n foo_check: /bin/true\n", format => 'yaml' } );
565  
566 =cut
567  
568 372 ▶sub new {
Subroutine new: called CC=13 SCAR=25.6
Pod documented
569 372 my %args;
570 372 ▶ if ( defined( $_[1] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[1]) 371 1 372
571 371 %args = %{ $_[1] };
572 }
573  
574 my $self = {
575 file => $args{file},
576 372 raw => undef,
577 format => 'sneck',
578 options => {},
579 vars => {},
580 env => [],
581 checks => {},
582 debugs => {},
583 restarts => {},
584 invalid_restarts => {},
585 compliance => {},
586 invalid_compliance => {},
587 errors => [],
588 warnings => [],
589 };
590 372 bless $self;
591  
592 372 ▶ if ( defined( $args{format} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $args{'format'}) { } 46 326 372
elsif (not defined $args{'raw'} and defined $args{'file'} and $args{'file'} =~ /\.[Yy][Aa]?[Mm][Ll]$/) { } 9 393 402
593 46 ▶ if ( $args{format} ne 'sneck' && $args{format} ne 'yaml' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"format"} ne "sneck" and $args{"format"} ne "yaml") 1 45 46
Condition100%3/3
$args{"format"} ne "sneck" and $args{"format"} ne "yaml"
!ll&&!rl&&r
1441
MC/DC100%2/2
$args{"format"} ne "sneck" and $args{"format"} ne "yaml"
$args{"format"} ne "sneck" $args{"format"} ne "yaml"
Truth table100%3/3
A and B
A= $args{"format"} ne "sneck"B= $args{"format"} ne "yaml"
ABresult
0X0
100
111
594 1 die( 'Unknown format "' . $args{format} . '"' );
595 }
596 45 $self->{format} = $args{format};
597 ▶ } elsif ( !defined( $args{raw} )
Condition100%6/6
not defined $args{"raw"} and defined $args{"file"} and $args{"file"} =~ /\.[Yy][Aa]?[Mm][Ll]$/
!ll&&!rl&&r
762419
not defined $args{"raw"} and defined $args{"file"}
!ll&&!rl&&r
742250
MC/DC100%3/3
not defined $args{"raw"} and defined $args{"file"} and $args{"file"} =~ /\.[Yy][Aa]?[Mm][Ll]$/
not defined $args{"raw"} defined $args{"file"} $args{"file"} =~ /\.[Yy][Aa]?[Mm][Ll]$/
Truth table100%4/4
not(A) and B and C
A= not defined $args{"raw"}B= defined $args{"file"}C= $args{"file"} =~ /\.[Yy][Aa]?[Mm][Ll]$/
ABCresult
0XX0
10X0
1100
1111
598 && defined( $args{file} )
599 && $args{file} =~ /\.[Yy][Aa]?[Mm][Ll]$/ )
600 {
601 9 $self->{format} = 'yaml';
602 }
603  
604 371 ▶ if ( defined( $args{raw} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $args{'raw'}) { } 117 254 371
elsif (defined $args{'file'}) { } 252 2 254
605 117 $self->{raw} = $args{raw};
606 } elsif ( defined( $args{file} ) ) {
607 252 eval { $self->{raw} = read_file( $args{file} ); };
608 252 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 12 240 252
609 12 die( 'Failed to read in the config file "' . $args{file} . '"... ' . $@ );
610 }
611 } else {
612 2 die('Neither file nor raw specified');
613 }
614  
615 357 ▶ if ( $self->{format} eq 'yaml' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'format'} eq 'yaml') { } 53 304 357
616 53 ▶ if ( !eval { require YAML::XS; 1 } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require YAML::XS; 1 } }) 1 52 53
617 1 die( 'YAML::XS is required for YAML configs... ' . $@ );
618 }
619 52 $self->_parse_yaml;
620 } else {
621 304 $self->_parse_sneck;
622 }
623  
624 356 return $self;
625 } ## end sub new
626  
627 =head2 file
628  
629 Returns the path to the config file read or undef if it was created
630 from a string.
631  
632 my $file = $config->file;
633  
634 =cut
635  
636 2 ▶sub file {
Subroutine file: called CC=1 SCAR=0.0
Pod documented
637 2 return $_[0]->{file};
638 }
639  
640 =head2 format
641  
642 Returns the format the config was parsed as, either 'sneck' or 'yaml'.
643  
644 my $format = $config->format;
645  
646 =cut
647  
648 10 ▶sub format {
Subroutine format: called CC=1 SCAR=0.0
Pod documented
649 10 return $_[0]->{format};
650 }
651  
652 =head2 raw
653  
654 Returns the raw config as a string, exactly as read.
655  
656 my $raw = $config->raw;
657  
658 =cut
659  
660 7 ▶sub raw {
Subroutine raw: called CC=1 SCAR=0.0
Pod documented
661 7 return $_[0]->{raw};
662 }
663  
664 =head2 is_valid
665  
666 Returns 1 if the config has no errors, otherwise 0. Warnings do not
667 affect this.
668  
669 if ( !$config->is_valid ) {
670 warn('config has errors');
671 }
672  
673 =cut
674  
675 256 ▶sub is_valid {
Subroutine is_valid: called CC=2 SCAR=6.9
Pod documented
676 256 ▶ if ( defined( $_[0]->{errors}[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_[0]{"errors"}[0]) 31 225 256
677 31 return 0;
678 }
679 225 return 1;
680 }
681  
682 =head2 errors
683  
684 Returns a list of errors found in the config. Each is a hash ref as
685 below.
686  
687 - where :: Where the problem is, for printing. For the sneck format
688 this is 'line N'. For YAML this is the path to the problem, such
689 as 'checks.foo', or 'YAML' for a YAML syntax error.
690  
691 - line :: The line number, starting at 1. Undef for YAML.
692  
693 - path :: The path to the problem, such as 'checks.foo'. Undef for
694 the sneck format.
695  
696 - text :: The line as it appears in the file. Undef for YAML.
697  
698 - message :: A description of the problem.
699  
700 For the sneck format these are in line order. For YAML they are in
701 section order, options, env, vars, checks, debugs, compliance, then
702 restarts, then by name.
703  
704 foreach my $error ( $config->errors ) {
705 print $error->{where} . ': ' . $error->{message} . "\n";
706 }
707  
708 =cut
709  
710 79 ▶sub errors {
Subroutine errors: called CC=1 SCAR=0.0
Pod documented
711 79 return @{ $_[0]->{errors} };
712 }
713  
714 =head2 warnings
715  
716 Returns a list of warnings found in the config. Same format and order
717 as errors.
718  
719 foreach my $warning ( $config->warnings ) {
720 print $warning->{where} . ': ' . $warning->{message} . "\n";
721 }
722  
723 =cut
724  
725 17 ▶sub warnings {
Subroutine warnings: called CC=1 SCAR=0.0
Pod documented
726 17 return @{ $_[0]->{warnings} };
727 }
728  
729 =head2 options
730  
731 Returns a hash ref of the options set in the config, with the names as
732 keys. Options not set are left out, so the caller can fall back to its
733 own defaults. Invalid ones are also left out. Values are in the
734 standard form described under validate_option. This is a copy, so
735 changing it does not change the config.
736  
737 my $cache_file = $config->options->{cache_file};
738  
739 =cut
740  
741 235 ▶sub options {
Subroutine options: called CC=1 SCAR=0.0
Pod documented
742 235 return { %{ $_[0]->{options} } };
743 }
744  
745 =head2 validate_option
746  
747 Validates a option value and puts it in a standard form, the same as is
748 done for the config. May be called on the class or a object.
749  
750 Two arguments are taken, the option name and the value.
751  
752 Returns two values. The first is the value in standard form or undef if
753 it is not valid. The second is undef if it is valid or a error message.
754  
755 The standard forms are as below.
756  
757 - locking, check_kill_sub_pids, compliance_alert :: 0 or 1.
758  
759 - check_timeout :: A number.
760  
761 - check_timeout_signal :: The signal name without the SIG prefix,
762 such as TERM. Numbers are turned into names.
763  
764 my ( $signal, $error ) = Monitoring::Sneck::Config->validate_option( 'check_timeout_signal', 'sigterm' );
765 # $signal is 'TERM' and $error is undef
766  
767 my ( $timeout, $error ) = Monitoring::Sneck::Config->validate_option( 'check_timeout', 0 );
768 # $timeout is undef and $error is 'option "check_timeout" must be a whole number of at least 1'
769  
770 =cut
771  
772 146 ▶sub validate_option {
Subroutine validate_option: called CC=18 SCAR=28.9
Pod documented
773 146 my ( $self, $name, $value ) = @_;
774  
775 146 ▶ if ( !defined($name) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $name) 1 145 146
776 1 return ( undef, 'no option name given' );
777 }
778  
779 145 my $label = 'option "' . $name . '"';
780  
781 145 my %known = map { $_ => 1 }
782 ( 'cache_file', 'pid_dir', 'locking', 'check_timeout', 'check_timeout_signal', 'check_kill_sub_pids', 'compliance_alert' );
783 145 ▶ if ( !$known{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($known{$name}) 3 142 145
784 3 return ( undef, 'unknown ' . $label );
785 }
786  
787 142 ▶ if ( ref($value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value) 4 138 142
788 4 return ( undef, $label . ' must be a string or number' );
789 }
790  
791 138 ▶ if ( $name eq 'locking' || $name eq 'check_kill_sub_pids' || $name eq 'compliance_alert' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "locking" or $name eq "check_kill_sub_pids" or $name eq "compliance_alert") 47 91 138
Condition100%6/6
$name eq "locking" or $name eq "check_kill_sub_pids" or $name eq "compliance_alert"
l!l&&r!l&&!r
41691
$name eq "locking" or $name eq "check_kill_sub_pids"
l!l&&r!l&&!r
182397
MC/DC100%3/3
$name eq "locking" or $name eq "check_kill_sub_pids" or $name eq "compliance_alert"
$name eq "locking" $name eq "check_kill_sub_pids" $name eq "compliance_alert"
Truth table100%4/4
A or B or C
A= $name eq "locking"B= $name eq "check_kill_sub_pids"C= $name eq "compliance_alert"
ABCresult
1XX1
01X1
0011
0000
792 47 ▶ if ( !defined($value) || $value !~ /^[01]?$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value and $value =~ /^[01]?$/) 8 39 47
Condition66%2/3
defined $value and $value =~ /^[01]?$/
!ll&&!rl&&r
0839
MC/DC50%1/2
defined $value and $value =~ /^[01]?$/
defined $value $value =~ /^[01]?$/
Truth table66%2/3
A and B
A= defined $valueB= $value =~ /^[01]?$/
ABresult
0X0
100
111
793 8 return ( undef, $label . ' must be 0 or 1' );
794 }
795 39 ▶ return ( $value ? 1 : 0, undef );
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 21 18 39
796 }
797  
798 91 ▶ if ( $name eq 'check_timeout' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "check_timeout") 35 56 91
799 35 ▶ if ( !defined($value) || $value !~ /^[0-9]+$/ || $value < 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value && $value =~ /^[0-9]+$/ or $value < 1) 10 25 35
Condition100%6/6
not defined $value && $value =~ /^[0-9]+$/ or $value < 1
l!l&&r!l&&!r
6425
defined $value && $value =~ /^[0-9]+$/
!ll&&!rl&&r
1529
MC/DC100%3/3
not defined $value && $value =~ /^[0-9]+$/ or $value < 1
defined $value $value =~ /^[0-9]+$/ $value < 1
Truth table100%4/4
not(A && B) or C
A= defined $valueB= $value =~ /^[0-9]+$/C= $value < 1
ABCresult
0XX1
10X1
1111
1100
800 10 return ( undef, $label . ' must be a whole number of at least 1' );
801 }
802 25 return ( $value + 0, undef );
803 }
804  
805 56 ▶ if ( $name eq 'check_timeout_signal' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "check_timeout_signal") 28 28 56
806 28 my $signal = $self->_signal_name($value);
807 28 ▶ if ( !defined($signal) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $signal) 8 20 28
808 8 return ( undef, $label . ' must be a signal name or a signal number other than 0' );
809 }
810 20 return ( $signal, undef );
811 }
812  
813 28 ▶ if ( !defined($value) || $value eq '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value or $value eq "") 5 23 28
Condition100%3/3
not defined $value or $value eq ""
l!l&&r!l&&!r
2323
MC/DC100%2/2
not defined $value or $value eq ""
not defined $value $value eq ""
Truth table100%3/3
not(A) or B
A= not defined $valueB= $value eq ""
ABresult
1X1
011
000
814 5 return ( undef, $label . ' may not be empty' );
815 }
816 23 return ( $value, undef );
817 } ## end sub validate_option
818  
819 =head2 vars
820  
821 Returns a hash ref of the variables, with the names as keys. This is a
822 copy, so changing it does not change the config.
823  
824 my $value = $config->vars->{GEOM_DEV};
825  
826 =cut
827  
828 223 ▶sub vars {
Subroutine vars: called CC=1 SCAR=0.0
Pod documented
829 223 return { %{ $_[0]->{vars} } };
830 }
831  
832 =head2 env
833  
834 Returns a array ref of environment variables to set, in the order they
835 should be set. Each item is a array ref of the name and value. This is
836 a copy, so changing it does not change the config.
837  
838 For the sneck format, the order is the order they appear in the config.
839 For YAML, it is sorted by name.
840  
841 Nothing is set in %ENV by this module. That is left to the caller.
842  
843 foreach my $env ( @{ $config->env } ) {
844 $ENV{ $env->[0] } = $env->[1];
845 }
846  
847 =cut
848  
849 198 ▶sub env {
Subroutine env: called CC=1 SCAR=0.0
Pod documented
850 198 return [ map { [ @{$_} ] } @{ $_[0]->{env} } ];
851 }
852  
853 =head2 checks
854  
855 Returns a hash ref of the checks, with the names as keys and the
856 commands, before variable substitution, as values. This is a copy, so
857 changing it does not change the config.
858  
859 my $command = $config->checks->{geom_foo};
860  
861 =cut
862  
863 220 ▶sub checks {
Subroutine checks: called CC=1 SCAR=0.0
Pod documented
864 220 return { %{ $_[0]->{checks} } };
865 }
866  
867 =head2 debugs
868  
869 Returns a hash ref of the debug checks. Same format as checks. The
870 names do not include the leading % used by the sneck format.
871  
872 my $command = $config->debugs->{routes};
873  
874 =cut
875  
876 204 ▶sub debugs {
Subroutine debugs: called CC=1 SCAR=0.0
Pod documented
877 204 return { %{ $_[0]->{debugs} } };
878 }
879  
880 =head2 restarts
881  
882 Returns a hash ref of the restarts, with the names as keys. Each value
883 is a hash ref with every option filled in, defaults included, as below.
884 This is a copy, so changing it does not change the config.
885  
886 - command :: The command, before variable substitution.
887  
888 - checks :: Array ref of the names of the checks watched.
889  
890 - depends :: Array ref of the names of the restarts depended on.
891  
892 - threshold, cascade, ignore_unknown, ignore_errored, min_interval,
893 max_retries, timeout, kill_sub_pids, check_restart,
894 check_restart_delay :: As described under
895 RESTARTS. The 0/1 options are always 0 or 1.
896  
897 - timeout_signal :: The signal name without the SIG prefix, such as
898 TERM, or undef if not set. Numbers are turned into names.
899  
900 - not_every :: The cron spec with surrounding whitespace removed and
901 other runs of whitespace turned into a single space, or undef if
902 not set.
903  
904 my $threshold = $config->restarts->{httpd}{threshold};
905  
906 =cut
907  
908 222 ▶sub restarts {
Subroutine restarts: called CC=3 SCAR=11.0
Pod documented
909 222 my %restarts;
910 222 foreach my $name ( keys( %{ $_[0]->{restarts} } ) ) {
911 234 ▶ if ( $_[0]->{invalid_restarts}{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]{"invalid_restarts"}{$name}) 49 185 234
912 49 next;
913 }
914 185 my $restart = $_[0]->{restarts}{$name};
915 185 $restarts{$name} = { %{$restart}, checks => [ @{ $restart->{checks} } ], depends => [ @{ $restart->{depends} } ] };
916 }
917 222 return \%restarts;
918 }
919  
920 =head2 compliance
921  
922 Returns a hash ref of the compliance checks, with the names as keys.
923 Each value is a hash ref with every option filled in, as below. This is
924 a copy, so changing it does not change the config.
925  
926 - command :: The command, before variable substitution.
927  
928 - control, framework, waived_until, waiver :: As described under
929 COMPLIANCE, or undef if not set.
930  
931 - severity :: Lower case, or undef if not set.
932  
933 - interval :: As described under COMPLIANCE.
934  
935 - timeout :: As described under COMPLIANCE, or undef if not set, in
936 which case check_timeout is used.
937  
938 my $control = $config->compliance->{ssh_no_root}{control};
939  
940 =cut
941  
942 200 ▶sub compliance {
Subroutine compliance: called CC=3 SCAR=11.0
Pod documented
943 200 my %compliance;
944 200 foreach my $name ( keys( %{ $_[0]->{compliance} } ) ) {
945 39 ▶ if ( $_[0]->{invalid_compliance}{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]{"invalid_compliance"}{$name}) 11 28 39
946 11 next;
947 }
948 28 $compliance{$name} = { %{ $_[0]->{compliance}{$name} } };
949 }
950 200 return \%compliance;
951 }
952  
953 =head2 substitute
954  
955 Takes a string, usually a check command, and returns it with the
956 variables put in place. Variables are put in place in sorted name
957 order. Undefined variables are left as written.
958  
959 my $ran = $config->substitute( $config->checks->{geom_foo} );
960  
961 =cut
962  
963 406 ▶sub substitute {
Subroutine substitute: called CC=2 SCAR=6.9
Pod documented
964 406 my $self = $_[0];
965 406 my $string = $_[1];
966  
967 406 foreach my $var_name ( sort( keys( %{ $self->{vars} } ) ) ) {
968 37 my $value = $self->{vars}{$var_name};
969 37 $string =~ s/%+$var_name%+/$value/g;
970 }
971  
972 406 return $string;
973 }
974  
975 # Parses $self->{raw} as the sneck format, filling in options, vars, env,
976 # checks, debugs, compliance, restarts, errors, and warnings. Called once by new. Takes no args and
977 # returns nothing.
978 #
979 # Lines are numbered from 1 so errors and warnings can point at them. All
980 # lines are looked at, so every error is reported, not just the first.
981 # Errors and warnings are sorted into line order at the end.
982 #
983 # Example...
984 #
985 # $self->{raw} = "FOO=bar\nbad line\n";
986 # $self->_parse_sneck;
987 # # $self->{vars} is { FOO => 'bar' }
988 # # $self->{errors} is [ { where => 'line 2', line => 2, path => undef, text => 'bad line',
989 # # message => '"bad line" is not a understood line' } ]
990 304 ▶sub _parse_sneck {
Subroutine _parse_sneck: called CC=20 SCAR=30.0
991 304 my $self = $_[0];
992  
993 # where each command was defined, for undefined variable warnings
994 304 my %command_locations;
995  
996 # options already given, even if invalid, so redefinitions are caught
997 my %option_seen;
998  
999 304 my $line_number = 0;
1000 304 foreach my $text ( split( /\n/, $self->{raw} ) ) {
1001 753 $line_number++;
1002 753 $text =~ s/\r$//;
1003  
1004 753 my $line = $text;
1005 753 $line =~ s/^[\ \t]*//;
1006  
1007 753 my $location = { line => $line_number, text => $text };
1008  
1009 753 ▶ if ( $line eq '' || $line =~ /^#/ ) {
Branch: 7 branches
BranchTrueFalseTotal
if ($line eq '' or $line =~ /^#/) { } 18 735 753
elsif ($line =~ /^[Ee][Nn][Vv]\ ([A-Za-z0-9\_]+)\=(.*)$/) { } 11 724 735
elsif ($line =~ /^\$([A-Za-z0-9\_]+)\=(.*)$/) { } 102 622 724
elsif ($line =~ /^([A-Za-z0-9\_]+)\=(.*)$/) { } 40 582 622
elsif ($line =~ /^(\%?)([A-Za-z0-9\_]+)\|(.*)$/) { } 313 269 582
elsif ($line =~ /^\@([A-Za-z0-9\_]+)\|([^\|]*)\|(.*)$/) { } 204 65 269
elsif ($line =~ /^\!([A-Za-z0-9\_]+)\|([^\|]*)\|(.*)$/) { } 47 18 65
Condition100%3/3
$line eq "" or $line =~ /^#/
l!l&&r!l&&!r
612735
MC/DC100%2/2
$line eq "" or $line =~ /^#/
$line eq "" $line =~ /^#/
Truth table100%3/3
A or B
A= $line eq ""B= $line =~ /^#/
ABresult
1X1
011
000
1010 # blank or comment
1011 18 next;
1012 } elsif ( $line =~ /^[Ee][Nn][Vv]\ ([A-Za-z0-9\_]+)\=(.*)$/ ) {
1013 11 push( @{ $self->{env} }, [ $1, $2 ] );
1014 } elsif ( $line =~ /^\$([A-Za-z0-9\_]+)\=(.*)$/ ) {
1015 102 my ( $name, $value ) = ( $1, $2 );
1016 102 ▶ if ( $option_seen{$name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($option_seen{$name}) 5 97 102
1017 5 $self->_add_problem( 'errors', $location, 'option "' . $name . '" is redefined' );
1018 5 next;
1019 }
1020 97 $option_seen{$name} = 1;
1021 97 $self->_add_option( $name, $value, $location );
1022 } elsif ( $line =~ /^([A-Za-z0-9\_]+)\=(.*)$/ ) {
1023 40 my ( $name, $value ) = ( $1, $2 );
1024 40 ▶ if ( defined( $self->{vars}{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"vars"}{$name}) 2 38 40
1025 2 $self->_add_problem( 'errors', $location, 'variable "' . $name . '" is redefined' );
1026 2 next;
1027 }
1028 38 $self->{vars}{$name} = $value;
1029 } elsif ( $line =~ /^(\%?)([A-Za-z0-9\_]+)\|(.*)$/ ) {
1030 313 my ( $type, $name, $command ) = ( 'checks', $2, $3 );
1031 313 ▶ if ( $1 eq '%' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($1 eq "%") 21 292 313
1032 21 $type = 'debugs';
1033 }
1034  
1035 313 ▶ if ( defined( $self->{$type}{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{$type}{$name}) 2 311 313
1036 2 $self->_add_problem( 'errors', $location, $self->_type_label($type) . ' "' . $name . '" is redefined' );
1037 2 next;
1038 }
1039  
1040 311 ▶ if ( $self->_add_command( $type, $name, $command, $location ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_add_command($type, $name, $command, $location)) 303 8 311
1041 303 $command_locations{$type}{$name} = $location;
1042 }
1043 } elsif ( $line =~ /^\@([A-Za-z0-9\_]+)\|([^\|]*)\|(.*)$/ ) {
1044 204 my ( $name, $options_string, $command ) = ( $1, $2, $3 );
1045  
1046 204 ▶ if ( defined( $self->{restarts}{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"restarts"}{$name}) 2 202 204
1047 2 $self->_add_problem( 'errors', $location, 'restart "' . $name . '" is redefined' );
1048 2 next;
1049 }
1050  
1051 # checks and depends are comma separated lists
1052 202 my ( $options, $options_good )
1053 = $self->_parse_line_options( 'restart "' . $name . '"', $options_string, $location, [ 'checks', 'depends' ] );
1054 # added even with bad options, so what it references is still checked
1055 202 $self->_add_restart( $name, $command, $options, $location );
1056 202 ▶ if ( !$options_good ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options_good) 7 195 202
1057 7 $self->{invalid_restarts}{$name} = 1;
1058 }
1059 202 $command_locations{restarts}{$name} = $location;
1060 } elsif ( $line =~ /^\!([A-Za-z0-9\_]+)\|([^\|]*)\|(.*)$/ ) {
1061 47 my ( $name, $options_string, $command ) = ( $1, $2, $3 );
1062  
1063 47 ▶ if ( defined( $self->{compliance}{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $self->{"compliance"}{$name}) 1 46 47
1064 1 $self->_add_problem( 'errors', $location, 'compliance check "' . $name . '" is redefined' );
1065 1 next;
1066 }
1067  
1068 46 my ( $options, $options_good )
1069 = $self->_parse_line_options( 'compliance check "' . $name . '"', $options_string, $location, [] );
1070 46 $self->_add_compliance( $name, $command, $options, $location );
1071 46 ▶ if ( !$options_good ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($options_good) 3 43 46
1072 3 $self->{invalid_compliance}{$name} = 1;
1073 }
1074 46 $command_locations{compliance}{$name} = $location;
1075 } else {
1076 18 $self->_add_problem( 'errors', $location, '"' . $line . '" is not a understood line' );
1077 }
1078 } ## end foreach my $text ( split( /\n/, $self->{raw} ) )
1079  
1080 304 $self->_validate_restarts( $command_locations{restarts} );
1081 304 $self->_warn_undefined_vars( \%command_locations );
1082  
1083 # keep errors and warnings in line order
1084 304 @{ $self->{errors} } = sort { $a->{line} <=> $b->{line} } @{ $self->{errors} };
1085 304 ▶ @{ $self->{warnings} } = sort { $a->{line} <=> $b->{line} || $a->{message} cmp $b->{message} } @{ $self->{warnings} };
Condition66%2/3
$Monitoring::Sneck::Config::a->{'line'} <=> $Monitoring::Sneck::Config::b->{'line'} || $Monitoring::Sneck::Config::a->{'message'} cmp $Monitoring::Sneck::Config::b->{'message'}
l!l&&r!l&&!r
330
MC/DC0%0/2
$Monitoring::Sneck::Config::a->{'line'} <=> $Monitoring::Sneck::Config::b->{'line'} || $Monitoring::Sneck::Config::a->{'message'} cmp $Monitoring::Sneck::Config::b->{'message'}
$Monitoring::Sneck::Config::a->{'line'} <=> $Monitoring::Sneck::Config::b->{'line'} $Monitoring::Sneck::Config::a->{'message'} cmp $Monitoring::Sneck::Config::b->{'message'}
Truth table66%2/3
A || B
A= $Monitoring::Sneck::Config::a->{'line'} <=> $Monitoring::Sneck::Config::b->{'line'}B= $Monitoring::Sneck::Config::a->{'message'} cmp $Monitoring::Sneck::Config::b->{'message'}
ABresult
1X1
011
000
1086  
1087 304 return;
1088 } ## end sub _parse_sneck
1089  
1090 # Parses the options part of a sneck format restart or compliance check
1091 # line into a hash ref of options. Used by _parse_sneck. Options are split
1092 # via _split_options, must be in the form key=value, and may not be given
1093 # more than once. Quotes are removed from values. Records a error for each
1094 # problem found. Unknown keys are left for the caller to catch.
1095 #
1096 # Args...
1097 #
1098 # - label :: What it is, for messages, such as 'restart "httpd"'.
1099 #
1100 # - options_string :: The text between the first and second | of the
1101 # line.
1102 #
1103 # - location :: Hash ref of where it was defined, as taken by
1104 # _add_problem.
1105 #
1106 # - list_keys :: Array ref of keys whose values are comma separated
1107 # lists, which are turned into array refs. May be empty.
1108 #
1109 # Returns a hash ref of the options that parsed, then 1 if there were no
1110 # problems or 0 if there were any.
1111 #
1112 # Example...
1113 #
1114 # my ( $options, $good ) = $self->_parse_line_options( 'restart "httpd"', 'checks=a,b threshold=2',
1115 # { line => 5, text => '...' }, [ 'checks', 'depends' ] );
1116 # # $options is { checks => [ 'a', 'b' ], threshold => 2 } and $good is 1
1117 #
1118 # ( $options, $good ) = $self->_parse_line_options( 'compliance check "ssh"', 'waiver="ticket 12" bogus',
1119 # { line => 6, text => '...' }, [] );
1120 # # $options is { waiver => 'ticket 12' }, $good is 0, and the error
1121 # # 'compliance check "ssh" option "bogus" is not in the form key=value' is added
1122 248 ▶sub _parse_line_options {
Subroutine _parse_line_options: called CC=7 SCAR=19.5
1123 248 my ( $self, $label, $options_string, $location, $list_keys ) = @_;
1124  
1125 248 my %is_list = map { $_ => 1 } @{$list_keys};
1126 248 my %options;
1127 248 my $options_good = 1;
1128 248 my ( $option_strings, $unterminated ) = $self->_split_options($options_string);
1129 248 ▶ if ( defined($unterminated) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $unterminated) 2 246 248
1130 2 $self->_add_problem( 'errors', $location, $label . ' has a unterminated quote in "' . $unterminated . '"' );
1131 2 $options_good = 0;
1132 }
1133 248 foreach my $option ( @{$option_strings} ) {
1134 447 ▶ if ( $option !~ /^([A-Za-z\_]+)\=(.*)$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($option =~ /^([A-Za-z\_]+)\=(.*)$/) 6 441 447
1135 6 $self->_add_problem( 'errors', $location, $label . ' option "' . $option . '" is not in the form key=value' );
1136 6 $options_good = 0;
1137 6 next;
1138 }
1139 441 my ( $key, $value ) = ( $1, $2 );
1140 441 ▶ $value =~ s/\"([^\"]*)\"|\'([^\']*)\'/defined($1) ? $1 : $2/ge;
Branch: 1 branch
BranchTrueFalseTotal
defined $1 ? : 21 3 24
1141 441 ▶ if ( exists( $options{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{$key}) 3 438 441
1142 3 $self->_add_problem( 'errors', $location, $label . ' option "' . $key . '" is given more than once' );
1143 3 $options_good = 0;
1144 3 next;
1145 }
1146 438 ▶ if ( $is_list{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_list{$key}) 240 198 438
1147 240 $value = [ split( /,/, $value, -1 ) ];
1148 }
1149 438 $options{$key} = $value;
1150 } ## end foreach my $option ( @{$option_strings} )
1151  
1152 248 return ( \%options, $options_good );
1153 } ## end sub _parse_line_options
1154  
1155 # Splits the options part of a sneck format restart or compliance check
1156 # line into its individual options. Used by _parse_line_options. Options are separated by spaces
1157 # or tabs, except inside " or ' quotes, which are left in place for the
1158 # caller to remove from the value.
1159 #
1160 # Args...
1161 #
1162 # - options_string :: The text between the first and second | of a
1163 # restart line.
1164 #
1165 # Returns a array ref of the option strings, quotes included, followed by
1166 # undef, or by the unparsed rest of the string starting at the first
1167 # quote that was never closed.
1168 #
1169 # Example...
1170 #
1171 # my ( $options, $unterminated ) = $self->_split_options(' checks=a not_every="* 0-3 * * *"');
1172 # # $options is [ 'checks=a', 'not_every="* 0-3 * * *"' ] and $unterminated is undef
1173 #
1174 # ( $options, $unterminated ) = $self->_split_options('checks=a not_every="* 0-3');
1175 # # $options is [ 'checks=a', 'not_every=' ] and $unterminated is '"* 0-3'
1176 248 ▶sub _split_options {
Subroutine _split_options: called CC=3 SCAR=11.0
1177 248 my ( $self, $options_string ) = @_;
1178  
1179 248 my @options;
1180 248 ▶ while ( $options_string =~ /\G[\ \t]*((?:[^\ \t\"\']+|\"[^\"]*\"|\'[^\']*\')+)/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options_string =~ /\G[\ \t]*((?:[^\ \t\"\']+|\"[^\"]*\"|\'[^\']*\')+)/cg) 447 248 695
1181 447 push( @options, $1 );
1182 }
1183  
1184 # anything left besides whitespace starts with a unclosed quote
1185 248 ▶ if ( $options_string =~ /\G[\ \t]*([^\ \t].*)$/gc ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($options_string =~ /\G[\ \t]*([^\ \t].*)$/cg) 2 246 248
1186 2 return ( \@options, $1 );
1187 }
1188  
1189 246 return ( \@options, undef );
1190 } ## end sub _split_options
1191  
1192 # Parses $self->{raw} as YAML, filling in options, vars, env, checks, debugs,
1193 # compliance, restarts, errors, and warnings. Called once by new after YAML::XS has been loaded.
1194 # Takes no args and returns nothing.
1195 #
1196 # YAML::XS gives no line numbers for keys, so problems point at a path
1197 # such as 'checks.foo' instead. A YAML syntax error is a single error with
1198 # the path 'YAML'. Sections are handled in the order options, env, vars,
1199 # checks, debugs, compliance, restarts, and names within them in sorted order, so problems come out in
1200 # a stable order.
1201 #
1202 # Example...
1203 #
1204 # $self->{raw} = "vars:\n FOO: bar\nchecks:\n foo_check: /bin/echo %FOO%\nbogus: 1\n";
1205 # $self->_parse_yaml;
1206 # # $self->{vars} is { FOO => 'bar' }
1207 # # $self->{checks} is { foo_check => '/bin/echo %FOO%' }
1208 # # $self->{errors} is [ { where => 'bogus', line => undef, path => 'bogus', text => undef,
1209 # # message => 'unknown top level key "bogus"' } ]
1210 52 ▶sub _parse_yaml {
Subroutine _parse_yaml: called CC=23 SCAR=31.4
1211 52 my $self = $_[0];
1212  
1213 52 my @documents;
1214 52 eval {
1215 # never let a config create perl objects
1216 60 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
1217 52 local $YAML::XS::LoadBlessed = 0;
1218 52 @documents = YAML::XS::Load( $self->{raw} );
1219 };
1220 52 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 51 52
1221 1 my $yaml_error = $@;
1222 1 $yaml_error =~ s/\s+/ /g;
1223 1 $yaml_error =~ s/^\s+|\s+$//g;
1224 1 $self->_add_problem( 'errors', { path => 'YAML' }, $yaml_error );
1225 1 return;
1226 }
1227  
1228 # an empty file or one with only comments is an empty config
1229 51 ▶ if ( !defined( $documents[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $documents[0]) 3 48 51
1230 3 return;
1231 }
1232  
1233 48 ▶ if ( defined( $documents[1] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $documents[1]) 1 47 48
1234 1 $self->_add_problem( 'errors', { path => 'YAML' }, 'only one YAML document is allowed' );
1235 1 return;
1236 }
1237  
1238 47 my $config = $documents[0];
1239 47 ▶ if ( ref($config) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $config ne "HASH") 3 44 47
1240 3 $self->_add_problem( 'errors', { path => 'YAML' }, 'the top level must be a mapping' );
1241 3 return;
1242 }
1243  
1244 44 my %known_sections = ( options => 1, env => 1, vars => 1, checks => 1, debugs => 1, compliance => 1, restarts => 1 );
1245 44 foreach my $key ( sort( keys( %{$config} ) ) ) {
1246 83 ▶ if ( !$known_sections{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($known_sections{$key}) 4 79 83
1247 4 $self->_add_problem( 'errors', { path => $key }, 'unknown top level key "' . $key . '"' );
1248 }
1249 }
1250  
1251 # where each command was defined, for undefined variable warnings
1252 44 my %command_locations;
1253  
1254 44 foreach my $section ( 'options', 'env', 'vars', 'checks', 'debugs', 'compliance', 'restarts' ) {
1255 308 my $items = $config->{$section};
1256 308 ▶ if ( !defined($items) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $items) 234 74 308
1257 234 next;
1258 }
1259 74 ▶ if ( ref($items) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $items ne "HASH") 5 69 74
1260 5 $self->_add_problem( 'errors', { path => $section }, 'must be a mapping' );
1261 5 next;
1262 }
1263  
1264 69 foreach my $name ( sort( keys( %{$items} ) ) ) {
1265 120 my $location = { path => $section . '.' . $name };
1266 120 my $value = $items->{$name};
1267  
1268 120 ▶ if ( $name !~ /^[A-Za-z0-9\_]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($name =~ /^[A-Za-z0-9\_]+$/) 5 115 120
1269 5 $self->_add_problem( 'errors', $location, 'name "' . $name . '" may only contain A-Z, a-z, 0-9, and _' );
1270 5 next;
1271 }
1272  
1273 # restarts are a mapping of options, with the command being one of them
1274 115 ▶ if ( $section eq 'restarts' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($section eq "restarts") 27 88 115
1275 27 $command_locations{restarts}{$name} = $location;
1276 27 ▶ if ( ref($value) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value ne "HASH") 2 25 27
1277 # still known, so restarts depending on it are not told it does not exist
1278 2 $self->_add_problem( 'errors', $location, 'value must be a mapping' );
1279 2 $self->{restarts}{$name} = { %{ $self->_restart_defaults }, command => '' };
1280 2 $self->{invalid_restarts}{$name} = 1;
1281 2 next;
1282 }
1283 25 my %options = %{$value};
1284 25 my $command = delete( $options{command} );
1285 25 $self->_add_restart( $name, $command, \%options, $location );
1286 25 next;
1287 } ## end if ( $section eq 'restarts' )
1288  
1289 # compliance checks are a mapping of options, with the command being one of them
1290 88 ▶ if ( $section eq 'compliance' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($section eq "compliance") 3 85 88
1291 3 $command_locations{compliance}{$name} = $location;
1292 3 ▶ if ( ref($value) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value ne "HASH") 1 2 3
1293 1 $self->_add_problem( 'errors', $location, 'value must be a mapping' );
1294 1 $self->{compliance}{$name} = { %{ $self->_compliance_defaults }, command => '' };
1295 1 $self->{invalid_compliance}{$name} = 1;
1296 1 next;
1297 }
1298 2 my %options = %{$value};
1299 2 my $command = delete( $options{command} );
1300 2 $self->_add_compliance( $name, $command, \%options, $location );
1301 2 next;
1302 } ## end if ( $section eq 'compliance' )
1303  
1304 85 ▶ if ( $section eq 'options' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($section eq "options") 20 65 85
1305 20 $self->_add_option( $name, $value, $location );
1306 20 next;
1307 }
1308  
1309 65 ▶ if ( ref($value) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value) 3 62 65
1310 3 $self->_add_problem( 'errors', $location, 'value must be a string or number' );
1311 3 next;
1312 }
1313  
1314 62 ▶ if ( $section eq 'env' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($section eq 'env') { } 6 56 62
elsif ($section eq 'vars') { } 17 39 56
1315 6 ▶ push( @{ $self->{env} }, [ $name, defined($value) ? $value : '' ] );
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 4 2 6
1316 } elsif ( $section eq 'vars' ) {
1317 17 ▶ $self->{vars}{$name} = defined($value) ? $value : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 16 1 17
1318 } else {
1319 39 ▶ if ( $self->_add_command( $section, $name, $value, $location ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_add_command($section, $name, $value, $location)) 32 7 39
1320 32 $command_locations{$section}{$name} = $location;
1321 }
1322 }
1323 } ## end foreach my $name ( sort( keys( %{$items} ) ) )
1324 } ## end foreach my $section ( 'options', 'env', 'vars', 'checks', 'debugs', 'compliance', 'restarts' )
1325  
1326 44 $self->_validate_restarts( $command_locations{restarts} );
1327 44 $self->_warn_undefined_vars( \%command_locations );
1328  
1329 44 return;
1330 } ## end sub _parse_yaml
1331  
1332 # Validates and adds a option via validate_option. Used by both parsers.
1333 # Records a error if the option is unknown or its value is bad, in which
1334 # case it is not added.
1335 #
1336 # Args...
1337 #
1338 # - name :: The name of the option, without the leading $ used by the
1339 # sneck format.
1340 #
1341 # - value :: The value, as taken by validate_option.
1342 #
1343 # - location :: Hash ref of where it was defined, as taken by
1344 # _add_problem.
1345 #
1346 # Returns 1 if it was added or 0 if there was a error.
1347 #
1348 # Example...
1349 #
1350 # $self->_add_option( 'locking', 1, { line => 2, text => '$locking=1' } );
1351 # # returns 1 and $self->{options}{locking} is 1
1352 #
1353 # $self->_add_option( 'pid_dir', '', { path => 'options.pid_dir' } );
1354 # # returns 0 and adds the error 'option "pid_dir" may not be empty'
1355 117 ▶sub _add_option {
Subroutine _add_option: called CC=2 SCAR=6.9
1356 117 my ( $self, $name, $value, $location ) = @_;
1357  
1358 117 my ( $validated, $error ) = $self->validate_option( $name, $value );
1359 117 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 25 92 117
1360 25 $self->_add_problem( 'errors', $location, $error );
1361 25 return 0;
1362 }
1363  
1364 92 $self->{options}{$name} = $validated;
1365 92 return 1;
1366 } ## end sub _add_option
1367  
1368 # Adds a check or debug check after making sure it has a command. Leading
1369 # spaces and tabs are removed from the command first. Used by both
1370 # parsers. Records a error if the command is empty.
1371 #
1372 # Args...
1373 #
1374 # - type :: Either 'checks' or 'debugs'.
1375 #
1376 # - name :: The name of the check, without any leading %.
1377 #
1378 # - command :: The command, possibly undef for YAML.
1379 #
1380 # - location :: Hash ref of where it was defined, as taken by
1381 # _add_problem.
1382 #
1383 # Returns 1 if it was added or 0 if the command was empty.
1384 #
1385 # Example...
1386 #
1387 # $self->_add_command( 'checks', 'foo', ' /bin/true', { line => 3, text => 'foo| /bin/true' } );
1388 # # returns 1 and $self->{checks}{foo} is '/bin/true'
1389 #
1390 # $self->_add_command( 'debugs', 'bar', undef, { path => 'debugs.bar' } );
1391 # # returns 0 and adds the error 'debug check "bar" has no command'
1392 350 ▶sub _add_command {
Subroutine _add_command: called CC=4 SCAR=13.9
1393 350 my ( $self, $type, $name, $command, $location ) = @_;
1394  
1395 350 ▶ if ( !defined($command) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $command) 2 348 350
1396 2 $command = '';
1397 }
1398 350 $command =~ s/^[\ \t]*//;
1399  
1400 350 ▶ if ( $command =~ /^\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($command =~ /^\s*$/) 12 338 350
1401 12 $self->_add_problem( 'errors', $location, $self->_type_label($type) . ' "' . $name . '" has no command' );
1402 12 return 0;
1403 }
1404  
1405 338 my $perl_problem = $self->_perl_check_problem($command);
1406 338 ▶ if ( defined($perl_problem) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $perl_problem) 3 335 338
1407 3 $self->_add_problem( 'errors', $location, $self->_type_label($type) . ' "' . $name . '" ' . $perl_problem );
1408 3 return 0;
1409 }
1410  
1411 335 $self->{$type}{$name} = $command;
1412 335 return 1;
1413 } ## end sub _add_command
1414  
1415 # Checks a command for problems as a perl check, see PERL CHECKS. Used by
1416 # _add_command and _add_compliance. Commands not starting with perl: are
1417 # not perl checks and are fine.
1418 #
1419 # Args...
1420 #
1421 # - command :: The command, with leading spaces and tabs removed.
1422 #
1423 # Returns undef if it is fine, else what is wrong, to follow the label of
1424 # what it is for.
1425 #
1426 # Example...
1427 #
1428 # $self->_perl_check_problem('perl:http -H www.example.org');
1429 # # undef
1430 #
1431 # $self->_perl_check_problem('perl:../http');
1432 # # 'has a perl check name that is not valid, it must be a-z, 0-9, and _, starting with a letter'
1433 #
1434 # $self->_perl_check_problem(q{perl:http -s 'Welcome});
1435 # # 'has unbalanced quotes in its perl check args'
1436 386 ▶sub _perl_check_problem {
Subroutine _perl_check_problem: called CC=5 SCAR=16.1
1437 386 my ( $self, $command ) = @_;
1438  
1439 386 ▶ if ( $command !~ /^perl:/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($command =~ /^perl:/) 377 9 386
1440 377 return undef;
1441 }
1442 9 my ( $check_name, $arg_string ) = $command =~ /^perl:(\S*)\s*(.*)$/s;
1443 9 ▶ if ( $check_name !~ /^[a-z][a-z0-9_]*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($check_name =~ /^[a-z][a-z0-9_]*$/) 3 6 9
1444 3 return 'has a perl check name that is not valid, it must be a-z, 0-9, and _, starting with a letter';
1445 }
1446  
1447 # eat unquoted runs, escaped characters, and whole quoted parts, until something does not close
1448 6 my $balanced_to = 0;
1449 6 ▶ while ( $arg_string =~ /\G(?:[^'"\\]+|\\.|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/gcs ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg_string =~ /\G(?:[^'"\\]+|\\.|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")/cgs) 6 6 12
1450 6 $balanced_to = pos($arg_string);
1451 }
1452 6 ▶ if ( $balanced_to != length($arg_string) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($balanced_to != length $arg_string) 1 5 6
1453 1 return 'has unbalanced quotes in its perl check args';
1454 }
1455  
1456 5 return undef;
1457 } ## end sub _perl_check_problem
1458  
1459 # Validates and adds a restart. Leading spaces and tabs are removed from
1460 # the command first. Used by both parsers. Records a error for every
1461 # problem found. Checks and depends are only checked for valid names here.
1462 # Whether they exist is checked by _validate_restarts once everything is
1463 # parsed.
1464 #
1465 # A restart with errors is still added, using the options that were good
1466 # plus defaults, and marked in $self->{invalid_restarts}. That way
1467 # _validate_restarts still checks what it references, and restarts that
1468 # depend on it are not wrongly told it does not exist. The restarts method
1469 # leaves invalid ones out.
1470 #
1471 # Args...
1472 #
1473 # - name :: The name of the restart.
1474 #
1475 # - command :: The command to run. For YAML this may be undef or, in
1476 # error, a reference.
1477 #
1478 # - options :: Hash ref of options. checks and depends are array refs
1479 # of names. The rest are scalars. Unknown keys are errors. YAML false
1480 # comes through as a empty string and is taken as 0.
1481 #
1482 # - location :: Hash ref of where it was defined, as taken by
1483 # _add_problem.
1484 #
1485 # Returns 1 if it was valid or 0 if there were any errors.
1486 #
1487 # Example...
1488 #
1489 # $self->_add_restart( 'httpd', '/usr/sbin/service apache24 restart',
1490 # { checks => [ 'http_check', 'php_check' ], threshold => 2 }, { line => 5, text => '...' } );
1491 # # returns 1 and $self->{restarts}{httpd} is
1492 # # { command => '/usr/sbin/service apache24 restart', checks => [ 'http_check', 'php_check' ],
1493 # # depends => [], threshold => 2, cascade => 0, ignore_unknown => 1, ignore_errored => 1,
1494 # # min_interval => 180, max_retries => 0, timeout => 30, timeout_signal => undef,
1495 # # kill_sub_pids => 1, check_restart => 0, check_restart_delay => 5, not_every => undef }
1496 227 ▶sub _add_restart {
Subroutine _add_restart: called CC=39 SCAR=36.6
1497 227 my ( $self, $name, $command, $options, $location ) = @_;
1498  
1499 227 my $label = 'restart "' . $name . '"';
1500 227 my $errors_before = scalar( @{ $self->{errors} } );
1501  
1502 227 my %restart = %{ $self->_restart_defaults };
1503  
1504 227 foreach my $key ( sort( keys( %{$options} ) ) ) {
1505 456 ▶ if ( !exists( $restart{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $restart{$key}) 2 454 456
1506 2 $self->_add_problem( 'errors', $location, $label . ' has unknown option "' . $key . '"' );
1507 }
1508 }
1509  
1510 227 foreach my $key ( 'checks', 'depends' ) {
1511 454 ▶ if ( !defined( $options->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $options->{$key}) 185 269 454
1512 185 next;
1513 }
1514 269 ▶ if ( ref( $options->{$key} ) ne 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $options->{$key} ne "ARRAY") 1 268 269
1515 1 $self->_add_problem( 'errors', $location, $label . ' option "' . $key . '" must be a list' );
1516 1 next;
1517 }
1518 268 my %seen;
1519 268 foreach my $item ( @{ $options->{$key} } ) {
1520 289 ▶ if ( !defined($item) || ref($item) || $item !~ /^[A-Za-z0-9\_]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $item or ref $item or not $item =~ /^[A-Za-z0-9\_]+$/) 6 283 289
Condition83%5/6
not defined $item or ref $item or not $item =~ /^[A-Za-z0-9\_]+$/
l!l&&r!l&&!r
15283
not defined $item or ref $item
l!l&&r!l&&!r
01288
MC/DC66%2/3
not defined $item or ref $item or not $item =~ /^[A-Za-z0-9\_]+$/
not defined $item ref $item not $item =~ /^[A-Za-z0-9\_]+$/
Truth table75%3/4
not(A) or B or not(C)
A= not defined $itemB= ref $itemC= not $item =~ /^[A-Za-z0-9\_]+$/
ABCresult
1XX1
01X1
0011
0000
1521 6 ▶ my $shown = defined($item) && !ref($item) ? $item : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $item && !ref($item) ? : 5 1 6
Condition66%2/3
defined $item and not ref $item
!ll&&!rl&&r
015
MC/DC50%1/2
defined $item and not ref $item
defined $item not ref $item
Truth table66%2/3
A and not(B)
A= defined $itemB= not ref $item
ABresult
0X0
100
111
1522 6 $self->_add_problem( 'errors', $location,
1523 $label . ' option "' . $key . '" has the invalid name "' . $shown . '"' );
1524 6 next;
1525 }
1526 283 ▶ if ( $seen{$item} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seen{$item}) 1 282 283
1527 1 $self->_add_problem( 'errors', $location,
1528 $label . ' option "' . $key . '" lists "' . $item . '" more than once' );
1529 1 next;
1530 }
1531 282 $seen{$item} = 1;
1532 282 push( @{ $restart{$key} }, $item );
1533 } ## end foreach my $item ( @{ $options->{$key} } )
1534 } ## end foreach my $key ( 'checks', 'depends' )
1535  
1536 227 ▶ if ( !defined( $options->{checks} )
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $options->{"checks"} or ref $options->{"checks"} eq "ARRAY" and not defined $options->{"checks"}[0]) 3 224 227
Condition100%6/6
not defined $options->{"checks"} or ref $options->{"checks"} eq "ARRAY" and not defined $options->{"checks"}[0]
l!l&&r!l&&!r
21224
ref $options->{"checks"} eq "ARRAY" and not defined $options->{"checks"}[0]
!ll&&!rl&&r
12231
MC/DC100%3/3
not defined $options->{"checks"} or ref $options->{"checks"} eq "ARRAY" and not defined $options->{"checks"}[0]
not defined $options->{"checks"} ref $options->{"checks"} eq "ARRAY" not defined $options->{"checks"}[0]
Truth table100%4/4
not(A) or B and not(C)
A= not defined $options->{"checks"}B= ref $options->{"checks"} eq "ARRAY"C= not defined $options->{"checks"}[0]
ABCresult
1XX1
0111
00X0
0100
1537 || ( ref( $options->{checks} ) eq 'ARRAY' && !defined( $options->{checks}[0] ) ) )
1538 {
1539 3 $self->_add_problem( 'errors', $location, $label . ' has no checks' );
1540 }
1541  
1542 227 foreach my $key ( 'cascade', 'ignore_unknown', 'ignore_errored', 'kill_sub_pids', 'check_restart' ) {
1543 1135 ▶ if ( !exists( $options->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options->{$key}) 1086 49 1135
1544 1086 next;
1545 }
1546 49 my $value = $options->{$key};
1547 49 ▶ if ( !defined($value) || ref($value) || $value !~ /^[01]?$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value or ref $value or not $value =~ /^[01]?$/) 10 39 49
Condition100%6/6
not defined $value or ref $value or not $value =~ /^[01]?$/
l!l&&r!l&&!r
2839
not defined $value or ref $value
l!l&&r!l&&!r
1147
MC/DC100%3/3
not defined $value or ref $value or not $value =~ /^[01]?$/
not defined $value ref $value not $value =~ /^[01]?$/
Truth table100%4/4
not(A) or B or not(C)
A= not defined $valueB= ref $valueC= not $value =~ /^[01]?$/
ABCresult
1XX1
01X1
0011
0000
1548 10 $self->_add_problem( 'errors', $location, $label . ' option "' . $key . '" must be 0 or 1' );
1549 10 next;
1550 }
1551 39 ▶ $restart{$key} = $value ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 27 12 39
1552 } ## end foreach my $key ( 'cascade', 'ignore_unknown', 'ignore_errored', 'kill_sub_pids', 'check_restart' )
1553  
1554 227 ▶ if ( exists( $options->{timeout_signal} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"timeout_signal"}) 23 204 227
1555 23 my $signal = $self->_signal_name( $options->{timeout_signal} );
1556 23 ▶ if ( defined($signal) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $signal) { } 9 14 23
1557 9 $restart{timeout_signal} = $signal;
1558 } else {
1559 14 $self->_add_problem( 'errors', $location,
1560 $label . ' option "timeout_signal" must be a signal name or a signal number other than 0' );
1561 }
1562 }
1563  
1564 227 ▶ if ( exists( $options->{not_every} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"not_every"}) 25 202 227
1565 25 my ( $spec, $error ) = $self->_parse_cron( $options->{not_every} );
1566 25 ▶ if ( defined($error) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) { } 11 14 25
1567 11 $self->_add_problem( 'errors', $location, $label . ' option "not_every" ' . $error );
1568 } else {
1569 14 $restart{not_every} = $spec;
1570 }
1571 }
1572  
1573 227 my %minimums = ( threshold => 1, min_interval => 0, max_retries => 0, timeout => 1, check_restart_delay => 0 );
1574 227 foreach my $key ( sort( keys(%minimums) ) ) {
1575 1135 ▶ if ( !exists( $options->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options->{$key}) 1047 88 1135
1576 1047 next;
1577 }
1578 88 my $value = $options->{$key};
1579 88 ▶ if ( !defined($value) || ref($value) || $value !~ /^[0-9]+$/ || $value < $minimums{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value or ref $value or not $value =~ /^[0-9]+$/ or $value < $minimums{$key}) 13 75 88
Condition88%8/9
not defined $value or ref $value or not $value =~ /^[0-9]+$/ or $value < $minimums{$key}
l!l&&r!l&&!r
8575
not defined $value or ref $value or not $value =~ /^[0-9]+$/
l!l&&r!l&&!r
1780
not defined $value or ref $value
l!l&&r!l&&!r
0187
MC/DC75%3/4
not defined $value or ref $value or not $value =~ /^[0-9]+$/ or $value < $minimums{$key}
not defined $value ref $value not $value =~ /^[0-9]+$/ $value < $minimums{$key}
Truth table80%4/5
not(A) or B or not(C) or D
A= not defined $valueB= ref $valueC= not $value =~ /^[0-9]+$/D= $value < $minimums{$key}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1580 $self->_add_problem( 'errors', $location,
1581 13 $label . ' option "' . $key . '" must be a whole number of at least ' . $minimums{$key} );
1582 13 next;
1583 }
1584 75 $restart{$key} = $value + 0;
1585 } ## end foreach my $key ( sort( keys(%minimums) ) )
1586  
1587 227 ▶ if ( defined( $restart{checks}[0] ) && $restart{threshold} > scalar( @{ $restart{checks} } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $restart{"checks"}[0] and $restart{"threshold"} > scalar @{$restart{"checks"};}) 1 226 227
Condition100%3/3
defined $restart{"checks"}[0] and $restart{"threshold"} > scalar @{$restart{"checks"};}
!ll&&!rl&&r
52211
MC/DC100%2/2
defined $restart{"checks"}[0] and $restart{"threshold"} > scalar @{$restart{"checks"};}
defined $restart{"checks"}[0] $restart{"threshold"} > scalar @{$restart{"checks"};}
Truth table100%3/3
A and B
A= defined $restart{"checks"}[0]B= $restart{"threshold"} > scalar @{$restart{"checks"};}
ABresult
0X0
100
111
1588 $self->_add_problem( 'errors', $location,
1589 $label
1590 . ' threshold of '
1591 . $restart{threshold}
1592 . ' is more than its '
1593 1 . scalar( @{ $restart{checks} } )
1594 . ' checks' );
1595 }
1596  
1597 227 ▶ if ( ref($command) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $command) { } 2 225 227
1598 2 $self->_add_problem( 'errors', $location, $label . ' option "command" must be a string' );
1599 2 $command = '';
1600 } else {
1601 225 ▶ if ( !defined($command) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $command) 1 224 225
1602 1 $command = '';
1603 }
1604 225 $command =~ s/^[\ \t]*//;
1605 225 ▶ if ( $command =~ /^\s*$/ ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($command =~ /^\s*$/) { } 3 222 225
elsif ($command =~ /^perl:/) { } 1 221 222
1606 3 $self->_add_problem( 'errors', $location, $label . ' has no command' );
1607 } elsif ( $command =~ /^perl:/ ) {
1608 1 $self->_add_problem( 'errors', $location, $label . ' can not be a perl check' );
1609 }
1610 }
1611  
1612 227 $restart{command} = $command;
1613 227 $self->{restarts}{$name} = \%restart;
1614  
1615 227 ▶ if ( scalar( @{ $self->{errors} } ) > $errors_before ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"errors"};} > $errors_before) 48 179 227
1616 48 $self->{invalid_restarts}{$name} = 1;
1617 48 return 0;
1618 }
1619  
1620 179 return 1;
1621 } ## end sub _add_restart
1622  
1623 # Returns the default options for a restart. Used by _add_restart and for
1624 # restarts too broken to parse at all.
1625 #
1626 # Returns a new hash ref each time, with empty checks and depends lists and
1627 # the default for every other option. No command is included.
1628 #
1629 # Example...
1630 #
1631 # my %restart = %{ $self->_restart_defaults };
1632 # # $restart{threshold} is 1 and $restart{min_interval} is 180
1633 229 ▶sub _restart_defaults {
Subroutine _restart_defaults: called CC=1 SCAR=0.0
1634 return {
1635 229 checks => [],
1636 depends => [],
1637 threshold => 1,
1638 cascade => 0,
1639 ignore_unknown => 1,
1640 ignore_errored => 1,
1641 min_interval => 180,
1642 max_retries => 0,
1643 timeout => 30,
1644 timeout_signal => undef,
1645 kill_sub_pids => 1,
1646 check_restart => 0,
1647 check_restart_delay => 5,
1648 not_every => undef,
1649 };
1650 } ## end sub _restart_defaults
1651  
1652 # Validates and adds a compliance check. Leading spaces and tabs are
1653 # removed from the command first. Used by both parsers. Records a error
1654 # for every problem found.
1655 #
1656 # A compliance check with errors is still added, using the options that
1657 # were good plus defaults, and marked in $self->{invalid_compliance}, so
1658 # redefinitions and undefined variables are still caught. The compliance
1659 # method leaves invalid ones out.
1660 #
1661 # Args...
1662 #
1663 # - name :: The name of the compliance check.
1664 #
1665 # - command :: The command to run. For YAML this may be undef or, in
1666 # error, a reference.
1667 #
1668 # - options :: Hash ref of options, all scalars. Unknown keys are
1669 # errors.
1670 #
1671 # - location :: Hash ref of where it was defined, as taken by
1672 # _add_problem.
1673 #
1674 # Returns 1 if it was valid or 0 if there were any errors.
1675 #
1676 # Example...
1677 #
1678 # $self->_add_compliance( 'ssh_no_root', 'sshd -T | grep -qi "^permitrootlogin no$"',
1679 # { control => 'CIS-5.2.10', severity => 'High' }, { line => 7, text => '...' } );
1680 # # returns 1 and $self->{compliance}{ssh_no_root} is
1681 # # { command => 'sshd -T | grep -qi "^permitrootlogin no$"', control => 'CIS-5.2.10',
1682 # # framework => undef, severity => 'high', interval => 0, timeout => undef,
1683 # # waived_until => undef, waiver => undef }
1684 #
1685 # $self->_add_compliance( 'telnet_off', '/bin/true', { waiver => 'ticket 12' }, { path => 'compliance.telnet_off' } );
1686 # # returns 0 and adds the error 'compliance check "telnet_off" option "waiver" needs waived_until'
1687 48 ▶sub _add_compliance {
Subroutine _add_compliance: called CC=27 SCAR=33.5
1688 48 my ( $self, $name, $command, $options, $location ) = @_;
1689  
1690 48 my $label = 'compliance check "' . $name . '"';
1691 48 my $errors_before = scalar( @{ $self->{errors} } );
1692  
1693 48 my %compliance = %{ $self->_compliance_defaults };
1694  
1695 48 foreach my $key ( sort( keys( %{$options} ) ) ) {
1696 53 ▶ if ( !exists( $compliance{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $compliance{$key}) 2 51 53
1697 2 $self->_add_problem( 'errors', $location, $label . ' has unknown option "' . $key . '"' );
1698 }
1699 }
1700  
1701 48 foreach my $key ( 'control', 'framework', 'waiver' ) {
1702 144 ▶ if ( !exists( $options->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options->{$key}) 127 17 144
1703 127 next;
1704 }
1705 17 my $value = $options->{$key};
1706 17 ▶ if ( !defined($value) || ref($value) || $value =~ /^\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value or ref $value or $value =~ /^\s*$/) 2 15 17
Condition50%3/6
not defined $value or ref $value or $value =~ /^\s*$/
l!l&&r!l&&!r
0215
not defined $value or ref $value
l!l&&r!l&&!r
0017
MC/DC33%1/3
not defined $value or ref $value or $value =~ /^\s*$/
not defined $value ref $value $value =~ /^\s*$/
Truth table50%2/4
not(A) or B or C
A= not defined $valueB= ref $valueC= $value =~ /^\s*$/
ABCresult
1XX1
01X1
0011
0000
1707 2 $self->_add_problem( 'errors', $location, $label . ' option "' . $key . '" must be a non-empty string' );
1708 2 next;
1709 }
1710 15 $compliance{$key} = $value;
1711 } ## end foreach my $key ( 'control', 'framework', 'waiver' )
1712  
1713 48 ▶ if ( exists( $options->{severity} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"severity"}) 5 43 48
1714 5 my $severity = $options->{severity};
1715 5 ▶ if ( defined($severity) && !ref($severity) && $severity =~ /^(low|medium|high|critical)$/i ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $severity and not ref $severity and $severity =~ /^(low|medium|high|critical)$/i) { } 4 1 5
Condition50%3/6
defined $severity and not ref $severity and $severity =~ /^(low|medium|high|critical)$/i
!ll&&!rl&&r
014
defined $severity and not ref $severity
!ll&&!rl&&r
005
MC/DC33%1/3
defined $severity and not ref $severity and $severity =~ /^(low|medium|high|critical)$/i
defined $severity not ref $severity $severity =~ /^(low|medium|high|critical)$/i
Truth table50%2/4
A and not(B) and C
A= defined $severityB= not ref $severityC= $severity =~ /^(low|medium|high|critical)$/i
ABCresult
0XX0
10X0
1100
1111
1716 4 $compliance{severity} = lc($severity);
1717 } else {
1718 1 $self->_add_problem( 'errors', $location,
1719 $label . ' option "severity" must be low, medium, high, or critical' );
1720 }
1721 }
1722  
1723 48 my %minimums = ( interval => 0, timeout => 1 );
1724 48 foreach my $key ( sort( keys(%minimums) ) ) {
1725 96 ▶ if ( !exists( $options->{$key} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $options->{$key}) 80 16 96
1726 80 next;
1727 }
1728 16 my $value = $options->{$key};
1729 16 ▶ if ( !defined($value) || ref($value) || $value !~ /^[0-9]+$/ || $value < $minimums{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $value or ref $value or not $value =~ /^[0-9]+$/ or $value < $minimums{$key}) 4 12 16
Condition66%6/9
not defined $value or ref $value or not $value =~ /^[0-9]+$/ or $value < $minimums{$key}
l!l&&r!l&&!r
3112
not defined $value or ref $value or not $value =~ /^[0-9]+$/
l!l&&r!l&&!r
0313
not defined $value or ref $value
l!l&&r!l&&!r
0016
MC/DC50%2/4
not defined $value or ref $value or not $value =~ /^[0-9]+$/ or $value < $minimums{$key}
not defined $value ref $value not $value =~ /^[0-9]+$/ $value < $minimums{$key}
Truth table60%3/5
not(A) or B or not(C) or D
A= not defined $valueB= ref $valueC= not $value =~ /^[0-9]+$/D= $value < $minimums{$key}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1730 $self->_add_problem( 'errors', $location,
1731 4 $label . ' option "' . $key . '" must be a whole number of at least ' . $minimums{$key} );
1732 4 next;
1733 }
1734 12 $compliance{$key} = $value + 0;
1735 } ## end foreach my $key ( sort( keys(%minimums) ) )
1736  
1737 48 ▶ if ( exists( $options->{waived_until} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"waived_until"}) 13 35 48
1738 13 ▶ if ( $self->_is_valid_date( $options->{waived_until} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_valid_date($options->{'waived_until'})) { } 8 5 13
1739 8 $compliance{waived_until} = $options->{waived_until};
1740 } else {
1741 5 $self->_add_problem( 'errors', $location,
1742 $label . ' option "waived_until" must be a valid date in the form YYYY-MM-DD' );
1743 }
1744 }
1745  
1746 48 ▶ if ( exists( $options->{waiver} ) && !exists( $options->{waived_until} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options->{"waiver"} and not exists $options->{"waived_until"}) 1 47 48
Condition100%3/3
exists $options->{"waiver"} and not exists $options->{"waived_until"}
!ll&&!rl&&r
4431
MC/DC100%2/2
exists $options->{"waiver"} and not exists $options->{"waived_until"}
exists $options->{"waiver"} not exists $options->{"waived_until"}
Truth table100%3/3
A and not(B)
A= exists $options->{"waiver"}B= not exists $options->{"waived_until"}
ABresult
0X0
100
111
1747 1 $self->_add_problem( 'errors', $location, $label . ' option "waiver" needs waived_until' );
1748 }
1749  
1750 48 ▶ if ( ref($command) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $command) { } 0 48 48
1751 0 $self->_add_problem( 'errors', $location, $label . ' option "command" must be a string' );
1752 0 $command = '';
1753 } else {
1754 48 ▶ if ( !defined($command) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $command) 0 48 48
1755 0 $command = '';
1756 }
1757 48 $command =~ s/^[\ \t]*//;
1758 48 ▶ if ( $command =~ /^\s*$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($command =~ /^\s*$/) 1 47 48
1759 1 $self->_add_problem( 'errors', $location, $label . ' has no command' );
1760 }
1761 48 my $perl_problem = $self->_perl_check_problem($command);
1762 48 ▶ if ( defined($perl_problem) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $perl_problem) 1 47 48
1763 1 $self->_add_problem( 'errors', $location, $label . ' ' . $perl_problem );
1764 }
1765 }
1766  
1767 48 $compliance{command} = $command;
1768 48 $self->{compliance}{$name} = \%compliance;
1769  
1770 48 ▶ if ( scalar( @{ $self->{errors} } ) > $errors_before ) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @{$self->{"errors"};} > $errors_before) 16 32 48
1771 16 $self->{invalid_compliance}{$name} = 1;
1772 16 return 0;
1773 }
1774  
1775 32 return 1;
1776 } ## end sub _add_compliance
1777  
1778 # Returns the default options for a compliance check. Used by
1779 # _add_compliance and for compliance checks too broken to parse at all.
1780 #
1781 # Returns a new hash ref each time, with the default for every option. No
1782 # command is included.
1783 #
1784 # Example...
1785 #
1786 # my %compliance = %{ $self->_compliance_defaults };
1787 # # $compliance{interval} is 0 and $compliance{control} is undef
1788 49 ▶sub _compliance_defaults {
Subroutine _compliance_defaults: called CC=1 SCAR=0.0
1789 return {
1790 49 control => undef,
1791 framework => undef,
1792 severity => undef,
1793 interval => 0,
1794 timeout => undef,
1795 waived_until => undef,
1796 waiver => undef,
1797 };
1798 } ## end sub _compliance_defaults
1799  
1800 # Checks if a value is a real calendar date in the form YYYY-MM-DD, as used
1801 # by waived_until. Leap years are taken into account.
1802 #
1803 # Args...
1804 #
1805 # - date :: The value from the config. May be undef or, in error, a
1806 # reference for YAML.
1807 #
1808 # Returns 1 if it is a valid date, otherwise 0.
1809 #
1810 # Example...
1811 #
1812 # $self->_is_valid_date('2028-02-29'); # 1
1813 # $self->_is_valid_date('2027-02-29'); # 0
1814 # $self->_is_valid_date('2027-2-1'); # 0
1815 13 ▶sub _is_valid_date {
Subroutine _is_valid_date: called CC=11 SCAR=24.2
1816 13 my ( $self, $date ) = @_;
1817  
1818 13 ▶ if ( !defined($date) || ref($date) || $date !~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $date or ref $date or not $date =~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/) 1 12 13
Condition50%3/6
not defined $date or ref $date or not $date =~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/
l!l&&r!l&&!r
0112
not defined $date or ref $date
l!l&&r!l&&!r
0013
MC/DC33%1/3
not defined $date or ref $date or not $date =~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/
not defined $date ref $date not $date =~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/
Truth table50%2/4
not(A) or B or not(C)
A= not defined $dateB= ref $dateC= not $date =~ /^([0-9]{4})-([0-9]{2})-([0-9]{2})$/
ABCresult
1XX1
01X1
0011
0000
1819 1 return 0;
1820 }
1821 12 my ( $year, $month, $day ) = ( $1, $2, $3 );
1822  
1823 12 my @days_in_month = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1824 12 ▶ if ( ( $year % 4 == 0 && $year % 100 != 0 ) || $year % 400 == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($year % 4 == 0 and $year % 100 != 0 or $year % 400 == 0) 4 8 12
Condition100%6/6
$year % 4 == 0 and $year % 100 != 0 or $year % 400 == 0
l!l&&r!l&&!r
228
$year % 4 == 0 and $year % 100 != 0
!ll&&!rl&&r
732
MC/DC100%3/3
$year % 4 == 0 and $year % 100 != 0 or $year % 400 == 0
$year % 4 == 0 $year % 100 != 0 $year % 400 == 0
Truth table80%4/5
A and B or C
A= $year % 4 == 0B= $year % 100 != 0C= $year % 400 == 0
ABCresult
11X1
0X11
1011
0X00
1000
1825 4 $days_in_month[1] = 29;
1826 }
1827  
1828 12 ▶ if ( $month < 1 || $month > 12 || $day < 1 || $day > $days_in_month[ $month - 1 ] ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($month < 1 or $month > 12 or $day < 1 or $day > $days_in_month[$month - 1]) 4 8 12
Condition77%7/9
$month < 1 or $month > 12 or $day < 1 or $day > $days_in_month[$month - 1]
l!l&&r!l&&!r
138
$month < 1 or $month > 12 or $day < 1
l!l&&r!l&&!r
1011
$month < 1 or $month > 12
l!l&&r!l&&!r
0111
MC/DC50%2/4
$month < 1 or $month > 12 or $day < 1 or $day > $days_in_month[$month - 1]
$month < 1 $month > 12 $day < 1 $day > $days_in_month[$month - 1]
Truth table60%3/5
A or B or C or D
A= $month < 1B= $month > 12C= $day < 1D= $day > $days_in_month[$month - 1]
ABCDresult
1XXX1
01XX1
001X1
00011
00000
1829 4 return 0;
1830 }
1831  
1832 8 return 1;
1833 } ## end sub _is_valid_date
1834  
1835 # Validates a cron spec, as used by not_every, and puts it in a standard
1836 # form. Used by _add_restart. DateTime::Event::Cron is only loaded the
1837 # first time this is called.
1838 #
1839 # Args...
1840 #
1841 # - spec :: The cron spec from the config. May be undef or, in error,
1842 # a reference for YAML.
1843 #
1844 # Returns two values. The first is the spec with surrounding whitespace
1845 # removed and other runs of whitespace turned into a single space, or
1846 # undef if it is not valid. The second is undef if it is valid, or the
1847 # end of a error message saying why it is not, to be put after the
1848 # option name.
1849 #
1850 # Example...
1851 #
1852 # my ( $spec, $error ) = $self->_parse_cron(' * 0-3 * * * ');
1853 # # $spec is '* 0-3 * * *' and $error is undef
1854 #
1855 # ( $spec, $error ) = $self->_parse_cron('* 0-30 * * *');
1856 # # $spec is undef and $error is 'is not a valid cron spec, Field value (30) out of range (0-23)'
1857 25 ▶sub _parse_cron {
Subroutine _parse_cron: called CC=7 SCAR=19.5
1858 25 my ( $self, $spec ) = @_;
1859  
1860 25 ▶ if ( !defined($spec) || ref($spec) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $spec or ref $spec) 2 23 25
Condition100%3/3
not defined $spec or ref $spec
l!l&&r!l&&!r
1123
MC/DC100%2/2
not defined $spec or ref $spec
not defined $spec ref $spec
Truth table100%3/3
not(A) or B
A= not defined $specB= ref $spec
ABresult
1X1
011
000
1861 2 return ( undef, 'must be a string' );
1862 }
1863  
1864 23 $spec =~ s/^\s+|\s+$//g;
1865 23 $spec =~ s/\s+/ /g;
1866  
1867 23 ▶ if ( !eval { require DateTime::Event::Cron; 1 } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { require DateTime::Event::Cron; 1 } }) 0 23 23
1868 0 return ( undef, 'needs DateTime::Event::Cron, which could not be loaded' );
1869 }
1870  
1871 23 my $cron = eval { DateTime::Event::Cron->new_from_cron( cron => $spec ) };
1872 23 ▶ if ( !defined($cron) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $cron) 8 15 23
1873 8 my $cron_error = $@;
1874 8 $cron_error =~ s/\s+at\s+\S+\s+line\s+\d+\.?\s*$//;
1875 8 $cron_error =~ s/\s+/ /g;
1876 8 $cron_error =~ s/^\s+|\s+$//g;
1877 8 $cron_error =~ s/\.$//;
1878 8 return ( undef, 'is not a valid cron spec, ' . $cron_error );
1879 }
1880  
1881 # anything past the fifth field is taken as a crontab command
1882 15 ▶ if ( defined( $cron->command ) && $cron->command ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cron->command and $cron->command ne "") 1 14 15
Condition66%2/3
defined $cron->command and $cron->command ne ""
!ll&&!rl&&r
0141
MC/DC50%1/2
defined $cron->command and $cron->command ne ""
defined $cron->command $cron->command ne ""
Truth table66%2/3
A and B
A= defined $cron->commandB= $cron->command ne ""
ABresult
0X0
100
111
1883 1 return ( undef, 'is not a valid cron spec, it must have exactly five fields' );
1884 }
1885  
1886 14 return ( $spec, undef );
1887 } ## end sub _parse_cron
1888  
1889 # Turns a signal given in a config into its name, as used by kill and
1890 # pkill. Known signals come from $Config{sig_name} and $Config{sig_num}, so
1891 # what is accepted matches the OS perl was built for.
1892 #
1893 # Args...
1894 #
1895 # - signal :: The signal from the config. A name, with or without the
1896 # SIG prefix and in any case, or a number. undef or a reference is
1897 # taken as invalid.
1898 #
1899 # Returns the upper case name without the SIG prefix, or undef if it is not
1900 # a known signal or is 0. If a number has more than one name, the first one
1901 # listed by $Config{sig_name} is used.
1902 #
1903 # Example...
1904 #
1905 # my $signal = $self->_signal_name('sigterm');
1906 # # $signal is 'TERM'
1907 #
1908 # my $signal = $self->_signal_name(9);
1909 # # $signal is 'KILL'
1910 #
1911 # my $signal = $self->_signal_name(0);
1912 # # $signal is undef
1913 51 ▶sub _signal_name {
Subroutine _signal_name: called CC=9 SCAR=22.0
1914 51 my ( $self, $signal ) = @_;
1915  
1916 51 ▶ if ( !defined($signal) || ref($signal) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $signal or ref $signal) 2 49 51
Condition100%3/3
not defined $signal or ref $signal
l!l&&r!l&&!r
1149
MC/DC100%2/2
not defined $signal or ref $signal
not defined $signal ref $signal
Truth table100%3/3
not(A) or B
A= not defined $signalB= ref $signal
ABresult
1X1
011
000
1917 2 return undef;
1918 }
1919  
1920 49 my @names = split( ' ', $Config{sig_name} );
1921 49 my @numbers = split( ' ', $Config{sig_num} );
1922 49 my %numbers_by_name;
1923 my %names_by_number;
1924 49 foreach my $index ( 0 .. $#names ) {
1925 3332 $numbers_by_name{ $names[$index] } = $numbers[$index];
1926 3332 ▶ if ( !exists( $names_by_number{ $numbers[$index] } ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $names_by_number{$numbers[$index]}) 3185 147 3332
1927 3185 $names_by_number{ $numbers[$index] } = $names[$index];
1928 }
1929 }
1930  
1931 49 my $name;
1932 49 ▶ if ( $signal =~ /^[0-9]+$/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($signal =~ /^[0-9]+$/) { } 11 38 49
1933 11 $name = $names_by_number{ $signal + 0 };
1934 } else {
1935 38 $name = uc($signal);
1936 38 $name =~ s/^SIG//;
1937 38 ▶ if ( !exists( $numbers_by_name{$name} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $numbers_by_name{$name}) 12 26 38
1938 12 $name = undef;
1939 }
1940 }
1941  
1942 49 ▶ if ( !defined($name) || $numbers_by_name{$name} == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $name or $numbers_by_name{$name} == 0) 20 29 49
Condition100%3/3
not defined $name or $numbers_by_name{$name} == 0
l!l&&r!l&&!r
12829
MC/DC100%2/2
not defined $name or $numbers_by_name{$name} == 0
not defined $name $numbers_by_name{$name} == 0
Truth table100%3/3
not(A) or B
A= not defined $nameB= $numbers_by_name{$name} == 0
ABresult
1X1
011
000
1943 20 return undef;
1944 }
1945  
1946 29 return $name;
1947 } ## end sub _signal_name
1948  
1949 # Checks the restarts against the rest of the config once everything is
1950 # parsed. Records a error for each watched check that does not exist,
1951 # each depend that does not exist, and each restart that is part of a
1952 # dependency cycle.
1953 #
1954 # Args...
1955 #
1956 # - restart_locations :: Hash ref of restart names to locations, as
1957 # taken by _add_problem. May be undef if there are no restarts.
1958 #
1959 # Returns nothing.
1960 #
1961 # Example...
1962 #
1963 # $self->{restarts}{a}{depends} = ['b'];
1964 # $self->{restarts}{b}{depends} = ['a'];
1965 # $self->_validate_restarts( { a => { line => 1, text => '...' }, b => { line => 2, text => '...' } } );
1966 # # adds the errors 'restart "a" has a dependency cycle: a -> b -> a' and
1967 # # 'restart "b" has a dependency cycle: b -> a -> b'
1968 348 ▶sub _validate_restarts {
Subroutine _validate_restarts: called CC=9 SCAR=22.0
1969 348 my ( $self, $restart_locations ) = @_;
1970  
1971 348 foreach my $name ( sort( keys( %{ $self->{restarts} } ) ) ) {
1972 229 my $restart = $self->{restarts}{$name};
1973 229 my $location = $restart_locations->{$name};
1974  
1975 229 foreach my $check ( @{ $restart->{checks} } ) {
1976 236 ▶ if ( !defined( $self->{checks}{$check} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"checks"}{$check}) 8 228 236
1977 8 my $message = 'restart "' . $name . '" watches unknown check "' . $check . '"';
1978 8 ▶ if ( defined( $self->{debugs}{$check} ) ) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $self->{'debugs'}{$check}) { } 2 6 8
elsif (defined $self->{'compliance'}{$check}) { } 1 5 6
1979 2 $message = $message . ', debug checks can not be watched';
1980 } elsif ( defined( $self->{compliance}{$check} ) ) {
1981 1 $message = $message . ', compliance checks can not be watched';
1982 }
1983 8 $self->_add_problem( 'errors', $location, $message );
1984 }
1985 }
1986  
1987 229 foreach my $depend ( @{ $restart->{depends} } ) {
1988 46 ▶ if ( !defined( $self->{restarts}{$depend} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"restarts"}{$depend}) 3 43 46
1989 3 $self->_add_problem( 'errors', $location,
1990 'restart "' . $name . '" depends on unknown restart "' . $depend . '"' );
1991 }
1992 }
1993  
1994 229 my $cycle = $self->_find_dependency_cycle($name);
1995 229 ▶ if ( defined($cycle) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cycle) 7 222 229
1996 $self->_add_problem( 'errors', $location,
1997 7 'restart "' . $name . '" has a dependency cycle: ' . join( ' -> ', @{$cycle} ) );
1998 }
1999 } ## end foreach my $name ( sort( keys( %{ $self->{restarts} } ) ) )
2000  
2001 348 return;
2002 } ## end sub _validate_restarts
2003  
2004 # Looks for a path through depends that leads from a restart back to
2005 # itself. Depends on unknown restarts are ignored. Searches breadth first,
2006 # so the shortest cycle is found.
2007 #
2008 # Args...
2009 #
2010 # - start :: The name of the restart to start from.
2011 #
2012 # Returns a array ref of the names in the cycle, starting and ending with
2013 # start, or undef if there is no cycle.
2014 #
2015 # Example...
2016 #
2017 # # a depends on b, b depends on c, c depends on a
2018 # my $cycle = $self->_find_dependency_cycle('a');
2019 # # $cycle is [ 'a', 'b', 'c', 'a' ]
2020 229 ▶sub _find_dependency_cycle {
Subroutine _find_dependency_cycle: called CC=5 SCAR=16.1
2021 229 my ( $self, $start ) = @_;
2022  
2023 229 my %visited;
2024 229 my @queue = map { [ $_, [ $start, $_ ] ] } @{ $self->{restarts}{$start}{depends} };
2025 229 ▶ while ( defined( $queue[0] ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $queue[0]) 60 222 282
2026 60 my ( $current, $path ) = @{ shift(@queue) };
2027 60 ▶ if ( $current eq $start ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($current eq $start) 7 53 60
2028 7 return $path;
2029 }
2030 53 ▶ if ( $visited{$current} || !defined( $self->{restarts}{$current} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($visited{$current} or not defined $self->{"restarts"}{$current}) 5 48 53
Condition100%3/3
$visited{$current} or not defined $self->{"restarts"}{$current}
l!l&&r!l&&!r
1448
MC/DC100%2/2
$visited{$current} or not defined $self->{"restarts"}{$current}
$visited{$current} not defined $self->{"restarts"}{$current}
Truth table100%3/3
A or not(B)
A= $visited{$current}B= not defined $self->{"restarts"}{$current}
ABresult
1X1
011
000
2031 5 next;
2032 }
2033 48 $visited{$current} = 1;
2034 48 push( @queue, map { [ $_, [ @{$path}, $_ ] ] } @{ $self->{restarts}{$current}{depends} } );
2035 }
2036  
2037 222 return undef;
2038 } ## end sub _find_dependency_cycle
2039  
2040 # Records a warning for each undefined variable used by each check, debug
2041 # check, compliance check, and restart command. Each variable is only warned about once per
2042 # command. Used by both parsers once everything is parsed, as variables
2043 # may be defined after the commands that use them.
2044 #
2045 # Args...
2046 #
2047 # - command_locations :: Hash ref of 'checks', 'debugs',
2048 # 'compliance', and 'restarts', each a hash ref of names to locations as taken by
2049 # _add_problem.
2050 #
2051 # Returns nothing.
2052 #
2053 # Example...
2054 #
2055 # $self->{checks}{foo} = '/bin/echo %NOPE%';
2056 # $self->_warn_undefined_vars( { checks => { foo => { line => 3, text => 'foo|/bin/echo %NOPE%' } } } );
2057 # # adds the warning 'check "foo" uses undefined variable "NOPE"' for line 3
2058 348 ▶sub _warn_undefined_vars {
Subroutine _warn_undefined_vars: called CC=8 SCAR=20.8
2059 348 my ( $self, $command_locations ) = @_;
2060  
2061 348 foreach my $type ( 'checks', 'debugs', 'compliance', 'restarts' ) {
2062 1392 foreach my $name ( sort( keys( %{ $self->{$type} } ) ) ) {
2063 613 my $command = $self->{$type}{$name};
2064 613 ▶ if ( $type eq 'restarts' || $type eq 'compliance' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "restarts" or $type eq "compliance") 278 335 613
Condition100%3/3
$type eq "restarts" or $type eq "compliance"
l!l&&r!l&&!r
22949335
MC/DC100%2/2
$type eq "restarts" or $type eq "compliance"
$type eq "restarts" $type eq "compliance"
Truth table100%3/3
A or B
A= $type eq "restarts"B= $type eq "compliance"
ABresult
1X1
011
000
2065 278 $command = $command->{command};
2066 }
2067 613 my %seen;
2068 613 ▶ while ( $command =~ /%+([A-Za-z0-9\_]+)(?=%)/g ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($command =~ /%+([A-Za-z0-9\_]+)(?=%)/g) 35 613 648
2069 35 my $var_name = $1;
2070 35 ▶ if ( !defined( $self->{vars}{$var_name} ) && !$seen{$var_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $self->{"vars"}{$var_name} or $seen{$var_name}) 20 15 35
Condition100%3/3
defined $self->{"vars"}{$var_name} or $seen{$var_name}
l!l&&r!l&&!r
13220
MC/DC100%2/2
defined $self->{"vars"}{$var_name} or $seen{$var_name}
defined $self->{"vars"}{$var_name} $seen{$var_name}
Truth table100%3/3
A or B
A= defined $self->{"vars"}{$var_name}B= $seen{$var_name}
ABresult
1X1
011
000
2071 20 $seen{$var_name} = 1;
2072 20 $self->_add_problem( 'warnings', $command_locations->{$type}{$name},
2073 $self->_type_label($type) . ' "' . $name . '" uses undefined variable "' . $var_name . '"' );
2074 }
2075 }
2076 } ## end foreach my $name ( sort( keys( %{ $self->{$type} } ) ) )
2077 } ## end foreach my $type ( 'checks', 'debugs', 'compliance', 'restarts' )
2078  
2079 348 return;
2080 } ## end sub _warn_undefined_vars
2081  
2082 # Returns the label used in messages for a type.
2083 #
2084 # Args...
2085 #
2086 # - type :: Either 'checks', 'debugs', 'compliance', or 'restarts'.
2087 #
2088 # Returns 'check' for 'checks', 'debug check' for 'debugs', 'compliance
2089 # check' for 'compliance', and 'restart' for 'restarts'.
2090 #
2091 # Example...
2092 #
2093 # my $label = $self->_type_label('debugs');
2094 # # $label is 'debug check'
2095 37 ▶sub _type_label {
Subroutine _type_label: called CC=4 SCAR=13.9
2096 37 ▶ if ( $_[1] eq 'debugs' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($_[1] eq 'debugs') { } 6 31 37
elsif ($_[1] eq 'restarts') { } 5 26 31
elsif ($_[1] eq 'compliance') { } 1 25 26
2097 6 return 'debug check';
2098 } elsif ( $_[1] eq 'restarts' ) {
2099 5 return 'restart';
2100 } elsif ( $_[1] eq 'compliance' ) {
2101 1 return 'compliance check';
2102 }
2103 25 return 'check';
2104 }
2105  
2106 # Records a error or warning. Returns nothing.
2107 #
2108 # Args...
2109 #
2110 # - kind :: Either 'errors' or 'warnings'.
2111 #
2112 # - location :: Hash ref of where the problem is. For the sneck format
2113 # this has 'line', the line number starting at 1, and 'text', the
2114 # line as it appears in the file. For YAML this has 'path', such as
2115 # 'checks.foo' or 'YAML'.
2116 #
2117 # - message :: A description of the problem.
2118 #
2119 # The recorded hash ref has where, line, path, text, and message, as
2120 # described in the POD for errors.
2121 #
2122 # Example...
2123 #
2124 # $self->_add_problem( 'errors', { line => 4, text => 'foo bar' }, '"foo bar" is not a understood line' );
2125 # # $self->{errors} now ends with
2126 # # { where => 'line 4', line => 4, path => undef, text => 'foo bar',
2127 # # message => '"foo bar" is not a understood line' }
2128 #
2129 # $self->_add_problem( 'errors', { path => 'checks.foo' }, 'check "foo" has no command' );
2130 # # $self->{errors} now ends with
2131 # # { where => 'checks.foo', line => undef, path => 'checks.foo', text => undef,
2132 # # message => 'check "foo" has no command' }
2133 229 ▶sub _add_problem {
Subroutine _add_problem: called CC=2 SCAR=6.9
2134 229 my ( $self, $kind, $location, $message ) = @_;
2135  
2136 229 my $where = $location->{path};
2137 229 ▶ if ( defined( $location->{line} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $location->{"line"}) 152 77 229
2138 152 $where = 'line ' . $location->{line};
2139 }
2140  
2141 push(
2142 229 @{ $self->{$kind} },
2143 {
2144 where => $where,
2145 line => $location->{line},
2146 path => $location->{path},
2147 text => $location->{text},
2148 229 message => $message,
2149 }
2150 );
2151 229 return;
2152 } ## end sub _add_problem
2153  
2154 =head1 BUGS
2155  
2156 Please report any bugs or feature requests to C<bug-monitoring-sneck at rt.cpan.org>, or through
2157 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Monitoring-Sneck>.
2158  
2159 =cut
2160  
2161 60 1; # End of Monitoring::Sneck::Config
« blib/lib/Monitoring/Sneck.pm ↑ Summary /usr/local/bin/perldoc »