blib/lib/Sagan/Monitoring.pm untested

filter: Statementstmt 0.0% 0 / 182 Branchbran 0.0% 0 / 70 Conditioncond 0.0% 0 / 38 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 12 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 305 CC 36 SCAR 57.8
CC
36
Cov
0%
run
600.0
new
72.0
print_output
42.0
CRAP 324.4
1 package Sagan::Monitoring;
2  
3 use 5.006;
4 use strict;
5 use warnings;
6 use JSON;
7 use File::Path qw(make_path);
8 use File::ReadBackwards;
9 use Carp;
10 use File::Slurp;
11 use Time::Piece;
12  
13 =head1 NAME
14  
15 Sagan::Monitoring - LibreNMS JSON SNMP extend and Nagios style check for Sagan stats
16  
17 =head1 VERSION
18  
19 Version 1.0.0
20  
21 =cut
22  
23 our $VERSION = '1.0.0';
24  
25 =head1 SYNOPSIS
26  
27 use Sagan::Monitoring;
28  
29 my $args = {
30 mode => 'librenms',
31 drop_percent_warn => .75;
32 drop_percent_crit => 1,
33 files=>{
34 'ids'=>'/var/log/sagan/alert-ids.json',
35 'foo'=>'/var/log/sagan/alert-foo.json',
36 },
37 };
38  
39 my $sm=Sagan::Monitoring->new( $args );
40 my $returned=$sm->run;
41 $sm->print;
42 exit $returned->{alert};
43  
44 =head1 METHODS
45  
46 =head2 new
47  
48 Initiate the object.
49  
50 The args are taken as a hash ref. The keys are documented as below.
51  
52 The only must have is 'files'.
53  
54 This assumes that stats-json.subtract_old_values is set to 'true'
55 for Suricata.
56  
57 - drop_percent_warn :: Drop percent warning threshold.
58 - Default :: .75;
59
60 - drop_percent_crit :: Drop percent critical threshold.
61 - Default :: 1
62
63 - files :: A hash with the keys being the instance name and the values
64 being the Eve files to read. ".total" is not a valid instance name.
65 Similarly anything starting with a "." should be considred reserved.
66  
67 my $args = {
68 drop_percent_warn => .75;
69 drop_percent_crit => 1,
70 mode => 'librenms',
71 files=>{
72 'ids'=>'/var/log/sagan/stats-ids.json',
73 'foo'=>'/var/log/sagan/stats-foo.json',
74 },
75 };
76  
77 my $sm=Sagan::Monitoring->new( $args );
78  
79 =cut
80  
81 sub new {
82 my %args;
83 if ( defined( $_[1] ) ) {
84 %args = %{ $_[1] };
85 }
86  
87 # init the object
88 my $self = {
89 'drop_percent_warn' => '.75',
90 'drop_percent_crit' => '1',
91 max_age => 360,
92 mode => 'librenms',
93 cache => '/var/cache/sagan_monitoring.json',
94 };
95 bless $self;
96  
97 # reel in the threshold values
98 my @thresholds = ( 'drop_percent_warn', 'drop_percent_crit' );
99 for my $threshold (@thresholds) {
100 if ( defined( $args{$threshold} ) ) {
101 $self->{$threshold} = $args{$threshold};
102 if ( $args{$threshold} !~ /[0-9\.]+/ ) {
103 confess( '"' . $threshold . '" with a value of "' . $args{$threshold} . '" is not numeric' );
104 }
105 }
106 }
107  
108 # get the mode and make sure it is valid
109 if (
110 defined( $args{mode} )
111 && ( ( $args{mode} ne 'librenms' )
112 && ( $args{mode} ne 'nagios' ) )
113 )
114 {
115 confess( '"' . $args{mode} . '" is not a understood mode' );
116 }
117 elsif ( defined( $args{mode} ) ) {
118 $self->{mode} = $args{mode};
119 }
120  
121 # make sure we have files specified
122 if ( ( !defined( $args{files} ) )
123 || ( !defined( keys( %{ $args{files} } ) ) ) )
124 {
125 confess('No files specified');
126 }
127 else {
128 $self->{files} = $args{files};
129 }
130  
131 if ( defined( $self->{files}{'.total'} ) ) {
132 confess('".total" is not a valid instance name');
133 }
134  
135 return $self;
136 }
137  
138 =head2 run
139  
140 This runs it and collects the data. Also updates the cache.
141  
142 This will return a LibreNMS style hash.
143  
144 my $returned=$sm->run;
145  
146 =cut
147  
148 sub run {
149 my $self = $_[0];
150  
151 # this will be returned
152 my $to_return = {
153 data => { '.total' => {} },
154 version => 1,
155 error => '0',
156 errorString => '',
157 alert => '0',
158 alertString => ''
159 };
160  
161 # figure out the time slot we care about
162 my $from = time;
163 my $till = $from - $self->{max_age};
164  
165 # process the files for each instance
166 my @instances = keys( %{ $self->{files} } );
167 my @alerts;
168 my $current_till;
169 foreach my $instance (@instances) {
170  
171 # ends processing for this file
172 my $process_it = 1;
173  
174 # open the file for reading it backwards
175 my $bw;
176 eval {
177 $bw = File::ReadBackwards->new( $self->{files}{$instance} )
178 or die( 'Can not read "' . $self->{files}{$instance} . '"... ' . $! );
179 };
180 if ($@) {
181 $to_return->{error} = '2';
182 if ( $to_return->{errorString} ne '' ) {
183 $to_return->{errorString} = $to_return->{errorString} . "\n";
184 }
185 $to_return->{errorString} = $to_return->{errorString} . $instance . ': ' . $@;
186 $process_it = 0;
187 }
188  
189 # get the first line, if possible
190 my $line;
191 if ($process_it) {
192 $line = $bw->readline;
193 }
194 while ( $process_it
195 && defined($line) )
196 {
197 eval {
198 my $json = decode_json($line);
199 my $timestamp = $json->{timestamp};
200  
201 # if current till is not set, set it
202 if ( !defined($current_till)
203 && defined($timestamp)
204 && $timestamp =~ /^[0-9]+\-[0-9]+\-[0-9]+T[0-9]+\:[0-9]+\:[0-9\.]+[\-\+][0-9]+/ )
205 {
206  
207 # get the number of hours
208 my $hours = $timestamp;
209 $hours =~ s/.*[\-\+]//g;
210 $hours =~ s/^0//;
211 $hours =~ s/[0-9][0-9]$//;
212  
213 # get the number of minutes
214 my $minutes = $timestamp;
215 $minutes =~ s/.*[\-\+]//g;
216 $minutes =~ s/^[0-9][0-9]//;
217  
218 my $second_diff = ( $minutes * 60 ) + ( $hours * 60 * 60 );
219  
220 if ( $timestamp =~ /\+/ ) {
221 $current_till = $till + $second_diff;
222 }
223 else {
224 $current_till = $till - $second_diff;
225 }
226 }
227 $timestamp =~ s/\..*$//;
228 my $t = Time::Piece->strptime( $timestamp, '%Y-%m-%dT%H:%M:%S' );
229  
230 # stop process further lines as we've hit the oldest we care about
231 if ( $t->epoch <= $current_till ) {
232 $process_it = 0;
233 }
234  
235 # we found the entry we are looking for if
236 # this matches, so process it
237 if ( defined( $json->{event_type} )
238 && $json->{event_type} eq 'stats' )
239 {
240 # we can stop processing now as this is what we were looking for
241 $process_it = 0;
242  
243 # holds the found new alerts
244 my @new_alerts;
245  
246 my $new_stats = {
247 uptime => $json->{stats}{uptime},
248 total => $json->{stats}{captured}{total},
249 drop => $json->{stats}{captured}{drop},
250 ignore => $json->{stats}{captured}{ignore},
251 threshold => $json->{stats}{captured}{threshold},
252 after => $json->{stats}{captured}{after},
253 match => $json->{stats}{captured}{match},
254 bytes => $json->{stats}{captured}{bytes_total},
255 bytes_ignored => $json->{stats}{captured}{bytes_ignored},
256 max_bytes_log_line => $json->{stats}{captured}{max_bytes_log_line},
257 eps => $json->{stats}{captured}{eps},
258 f_total => $json->{stats}{flow}{total},
259 f_dropped => $json->{stats}{flow}{dropped},
260 alert => 0,
261 alertString => '',
262 };
263  
264 # find the drop percentages
265 if ( $new_stats->{total} != 0 ) {
266 $new_stats->{drop_percent} = ( $new_stats->{drop} / $new_stats->{total} ) * 100;
267 $new_stats->{drop_percent} = sprintf( '%0.5f', $new_stats->{drop_percent} );
268 }
269 else {
270 $new_stats->{total_percent} = 0;
271 }
272 if ( $new_stats->{f_total} != 0 ) {
273 $new_stats->{f_drop_percent}
274 = ( $new_stats->{f_dropped} / $new_stats->{f_total} ) * 100;
275 $new_stats->{f_drop_percent} = sprintf( '%0.5f', $new_stats->{f_drop_percent} );
276 }
277 else {
278 $new_stats->{f_drop_percent} = 0;
279 }
280  
281 # check for drop percent alerts
282 if ( $new_stats->{drop_percent} >= $self->{drop_percent_warn}
283 && $new_stats->{drop_percent} < $self->{drop_percent_crit} )
284 {
285 $new_stats->{alert} = 1;
286 push( @new_alerts,
287 $instance
288 . ' drop_percent warning '
289 . $new_stats->{drop_percent} . ' >= '
290 . $self->{drop_percent_warn} );
291 }
292 if ( $new_stats->{drop_percent} >= $self->{drop_percent_crit} ) {
293 $new_stats->{alert} = 2;
294 push( @new_alerts,
295 $instance
296 . ' drop_percent critical '
297 . $new_stats->{drop_percent} . ' >= '
298 . $self->{drop_percent_crit} );
299 }
300  
301 # check for f_drop percent alerts
302 if ( $new_stats->{f_drop_percent} >= $self->{drop_percent_warn}
303 && $new_stats->{f_drop_percent} < $self->{drop_percent_crit} )
304 {
305 $new_stats->{alert} = 1;
306 push( @new_alerts,
307 $instance
308 . ' f_drop_percent warning '
309 . $new_stats->{f_drop_percent} . ' >= '
310 . $self->{drop_percent_warn} );
311 }
312 if ( $new_stats->{f_drop_percent} >= $self->{drop_percent_crit} ) {
313 $new_stats->{alert} = 2;
314 push( @new_alerts,
315 $instance
316 . ' f_drop_percent critical '
317 . $new_stats->{f_drop_percent} . ' >= '
318 . $self->{drop_percent_crit} );
319 }
320  
321 # add stuff to .total
322 my @intance_keys = keys( %{$new_stats} );
323 foreach my $total_key (@intance_keys) {
324 if ( $total_key ne 'alertString' && $total_key ne 'alert' ) {
325 if ( !defined( $to_return->{data}{'.total'}{$total_key} ) ) {
326 $to_return->{data}{'.total'}{$total_key} = $new_stats->{$total_key};
327 }
328 else {
329 $to_return->{data}{'.total'}{$total_key}
330 = $to_return->{data}{'.total'}{$total_key} + $new_stats->{$total_key};
331 }
332 }
333 }
334  
335 $to_return->{data}{$instance} = $new_stats;
336 }
337  
338 };
339  
340 # get the next line
341 $line = $bw->readline;
342 }
343  
344 }
345  
346 # find the drop percentages
347 if ( $to_return->{data}{'.total'}{total} != 0 ) {
348 $to_return->{data}{'.total'}{drop_percent}
349 = ( $to_return->{data}{'.total'}{drop} / $to_return->{data}{'.total'}{total} ) * 100;
350 $to_return->{data}{'.total'}{drop_percent} = sprintf( '%0.5f', $to_return->{data}{'.total'}{drop_percent} );
351 }
352 else {
353 $to_return->{data}{'.total'}{drop_percent} = 0;
354 }
355 if ( $to_return->{data}{'.total'}{f_dropped} != 0 ) {
356 $to_return->{data}{'.total'}{f_drop_percent}
357 = ( $to_return->{data}{'.total'}{f_dropped} / $to_return->{data}{'.total'}{f_total} ) * 100;
358 $to_return->{data}{'.total'}{f_drop_percent} = sprintf( '%0.5f', $to_return->{data}{'.total'}{f_drop_percent} );
359 }
360 else {
361 $to_return->{data}{'.total'}{f_drop_percent} = 0;
362 }
363  
364 # check for drop percent alerts
365 if ( $to_return->{data}{'.total'}{drop_percent} >= $self->{drop_percent_warn}
366 && $to_return->{data}{'.total'}{drop_percent} < $self->{drop_percent_crit} )
367 {
368 $to_return->{alert} = 1;
369 push( @alerts,
370 'total drop_percent warning '
371 . $to_return->{data}{'.total'}{drop_percent} . ' >= '
372 . $self->{drop_percent_warn} );
373 }
374 if ( $to_return->{data}{'.total'}{drop_percent} >= $self->{drop_percent_crit} ) {
375 $to_return->{alert} = 2;
376 push( @alerts,
377 'total drop_percent critical '
378 . $to_return->{data}{'.total'}{drop_percent} . ' >= '
379 . $self->{drop_percent_crit} );
380 }
381  
382 # check for f_drop percent alerts
383 if ( $to_return->{data}{'.total'}{f_drop_percent} >= $self->{drop_percent_warn}
384 && $to_return->{data}{'.total'}{f_drop_percent} < $self->{drop_percent_crit} )
385 {
386 $to_return->{alert} = 1;
387 push( @alerts,
388 'total f_drop_percent warning '
389 . $to_return->{data}{'.total'}{f_drop_percent} . ' >= '
390 . $self->{drop_percent_warn} );
391 }
392 if ( $to_return->{data}{'.total'}{f_drop_percent} >= $self->{drop_percent_crit} ) {
393 $to_return->{alert} = 2;
394 push( @alerts,
395 'total f_drop_percent critical '
396 . $to_return->{data}{'.total'}{f_drop_percent} . ' >= '
397 . $self->{drop_percent_crit} );
398 }
399  
400 # join any found alerts into the string
401 $to_return->{alertString} = join( "\n", @alerts );
402 $to_return->{data}{'.total'}{alert} = $to_return->{'alert'};
403  
404 # write the cache file on out
405 eval {
406 my $json = JSON->new->utf8->canonical(1);
407 my $new_cache = $json->encode($to_return) . "\n";
408 open( my $fh, '>', $self->{cache} );
409 print $fh $new_cache;
410 close($fh);
411 };
412 if ($@) {
413 $to_return->{error} = '1';
414 $to_return->{alert} = '3';
415 $to_return->{errorString} = 'Failed to write new cache JSON file, "' . $self->{cache} . '".... ' . $@;
416  
417 # set the nagious style alert stuff
418 $to_return->{alert} = '3';
419 if ( $to_return->{alertString} eq '' ) {
420 $to_return->{alertString} = $to_return->{errorString};
421 }
422 else {
423 $to_return->{alertString} = $to_return->{errorString} . "\n" . $to_return->{alertString};
424 }
425 }
426  
427 $self->{results} = $to_return;
428  
429 return $to_return;
430 }
431  
432 =head2 print_output
433  
434 Prints the output.
435 $sm->print_output;
436  
437 =cut
438  
439 sub print_output {
440 my $self = $_[0];
441  
442 if ( $self->{mode} eq 'nagios' ) {
443 if ( $self->{results}{alert} eq '0' ) {
444 print "OK - no alerts\n";
445 return;
446 }
447 elsif ( $self->{results}{alert} eq '1' ) {
448 print 'WARNING - ';
449 }
450 elsif ( $self->{results}{alert} eq '2' ) {
451 print 'CRITICAL - ';
452 }
453 elsif ( $self->{results}{alert} eq '3' ) {
454 print 'UNKNOWN - ';
455 }
456 my $alerts = $self->{results}{alertString};
457 chomp($alerts);
458 $alerts = s/\n/\, /g;
459 print $alerts. "\n";
460 }
461 else {
462 my $json = JSON->new->utf8->canonical(1);
463 print $json->encode( $self->{results} ) . "\n";
464 }
465 }
466  
467 =head1 LibreNMS HASH
468  
469 + $hash{'alert'} :: Alert status.
470 - 0 :: OK
471 - 1 :: WARNING
472 - 2 :: CRITICAL
473 - 3 :: UNKNOWN
474
475 + $hash{'alertString'} :: A string describing the alert. Defaults to
476 '' if there is no alert.
477
478 + $hash{'error'} :: A integer representing a error. '0' represents
479 everything is fine.
480
481 + $hash{'errorString'} :: A string description of the error.
482
483 + $hash{'data'}{$instance} :: Values migrated from the
484 instance. Non *_percent values are created via computing the difference
485 from the previously saved info. *_percent is based off of the delta
486 in question over the packet delta. Delta are created for packet,
487 drop, ifdrop, and error. Percents are made for drop, ifdrop, and
488 error.
489
490 + $hash{'data'}{'.total'} :: Total values of from all the
491 intances. Any percents will be recomputed.
492
493  
494 The stat keys are migrated as below.
495
496 uptime => $json->{stats}{uptime},
497 total => $json->{stats}{captured}{total},
498 drop => $json->{stats}{captured}{drop},
499 ignore => $json->{stats}{captured}{ignore},
500 threshold => $json->{stats}{captured}{theshold},
501 after => $json->{stats}{captured}{after},
502 match => $json->{stats}{captured}{match},
503 bytes => $json->{stats}{captured}{bytes_total},
504 bytes_ignored => $json->{stats}{captured}{bytes_ignored},
505 max_bytes_log_line => $json->{stats}{captured}{max_bytes_log_line},
506 eps => $json->{stats}{captured}{eps},
507 f_total => $json->{stats}{flow}{total},
508 f_dropped => $json->{stats}{flow}{dropped},
509  
510 =head1 AUTHOR
511  
512 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.net> >>
513  
514 =head1 BUGS
515  
516 Please report any bugs or feature requests to C<bug-sagan-monitoring at rt.cpan.org>, or through
517 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sagan-Monitoring>. I will be notified, and then you'll
518 automatically be notified of progress on your bug as I make changes.
519  
520  
521  
522  
523 =head1 SUPPORT
524  
525 You can find documentation for this module with the perldoc command.
526  
527 perldoc Sagan::Monitoring
528  
529  
530 You can also look for information at:
531  
532 =over 4
533  
534 =item * RT: CPAN's request tracker (report bugs here)
535  
536 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Sagan-Monitoring>
537  
538 =item * CPAN Ratings
539  
540 L<https://cpanratings.perl.org/d/Sagan-Monitoring>
541  
542 =item * Search CPAN
543  
544 L<https://metacpan.org/release/Sagan-Monitoring>
545  
546 =back
547  
548 =head * Git
549  
550 L<git@github.com:VVelox/Sagan-Monitoring.git>
551  
552 =item * Web
553  
554 L<https://github.com/VVelox/Sagan-Monitoring>
555  
556 =head1 ACKNOWLEDGEMENTS
557  
558  
559 =head1 LICENSE AND COPYRIGHT
560  
561 This software is Copyright (c) 2022 by Zane C. Bowers-Hadley.
562  
563 This is free software, licensed under:
564  
565 The Artistic License 2.0 (GPL Compatible)
566  
567  
568 =cut
569  
570 1; # End of Sagan::Monitoring