MonM/Daemon.pm untested

filter: Statementstmt 0.0% 0 / 267 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 93 MC/DCmcdc 0.0% 0 / 48 Subroutinesub 0.0% 0 / 31 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 563 CC 54 SCAR 46.4
CC
54
Cov
0%
slave
272.0
notify
182.0
run
132.0
CRAP 103.8
1 package App::MonM::Daemon;
2 use strict;
3 use utf8;
4  
5 =encoding utf8
6  
7 =head1 NAME
8  
9 App::MonM::Daemon - The daemon class of the MonM
10  
11 =head1 VERSION
12  
13 Version 1.01
14  
15 =head1 SYNOPSIS
16  
17 use App::MonM::Daemon;
18  
19 =head1 DESCRIPTION
20  
21 The daemon class of the MonM
22  
23 =head2 new
24  
25 my $daemon = App::MonM::Daemon->new('foo', (
26 loglevel => $loglevel,
27 forks => 3,
28 ));
29  
30 =head2 checker
31  
32 my $checker = $daemon->checker();
33  
34 Returns checker object
35  
36 =head2 cleanup
37  
38 This is internal method of the CTK::Daemon context
39  
40 =head2 down
41  
42 This is internal method of the CTK::Daemon context
43  
44 =head2 init
45  
46 This is internal method of the CTK::Daemon context
47  
48 =head2 notifier
49  
50 my $notifier = $daemon->notifier;
51  
52 Returns the Notifier object
53  
54 =head2 notify
55  
56 $daemon->notify();
57  
58 Sends notifications
59  
60 =head2 reload
61  
62 This is internal method of the CTK::Daemon context
63  
64 =head2 remind
65  
66 Performs notification's remind. This is proxy function of the Notifier class
67  
68 =head2 run
69  
70 This is internal method of the CTK::Daemon context
71  
72 =head2 slave
73  
74 Performs checking. Returns true/false as status
75  
76 =head2 store
77  
78 my $store = $daemon->store();
79  
80 Returns store object
81  
82 =head2 trigger
83  
84 my @errors = $daemon->trigger();
85  
86 Runs triggers
87  
88 =head1 HISTORY
89  
90 See C<Changes> file
91  
92 =head1 TO DO
93  
94 See C<TODO> file
95  
96 =head1 SEE ALSO
97  
98 L<CTK::App>, L<CTK::Daemon>
99  
100 =head1 AUTHOR
101  
102 Serż Minus (Sergey Lepenkov) L<https://www.serzik.com> E<lt>abalama@cpan.orgE<gt>
103  
104 =head1 COPYRIGHT
105  
106 Copyright (C) 1998-2022 D&D Corporation. All Rights Reserved
107  
108 =head1 LICENSE
109  
110 This program is free software; you can redistribute it and/or
111 modify it under the same terms as Perl itself.
112  
113 See C<LICENSE> file and L<https://dev.perl.org/licenses/>
114  
115 =cut
116  
117  
118 use vars qw/$VERSION/;
119 $VERSION = '1.01';
120  
121 use parent qw/CTK::Daemon/;
122  
123 use AnyEvent;
124 use File::Spec;
125  
126 use CTK::ConfGenUtil;
127 use CTK::TFVals qw/ :ALL /;
128 use CTK::Util qw/ preparedir dformat execute /;
129  
130 use App::MonM::Const;
131 use App::MonM::Util qw/
132 getBit setBit
133 node2anode getCheckitByName
134 getExpireOffset getTimeOffset
135 /;
136 use App::MonM::Store;
137 use App::MonM::Checkit;
138 use App::MonM::QNotifier;
139 use App::MonM::Report;
140  
141 use constant {
142 START_DELAY => 3,
143 INTERVAL_CTRL => 3, # 3 sec
144 INTERVAL_MAIN => 20, # 20 sec
145 INTERVAL_REMIND => 60, # 1 min
146 DAEMONFORKS => 3,
147 EXPIRES => 24*60*60, # 1 day
148 };
149  
150 eval { require App::MonM::Notifier };
151 my $NOTIFIER_LOADED = 1 unless $@;
152 $NOTIFIER_LOADED = 0 if $NOTIFIER_LOADED && (App::MonM::Notifier->VERSION * 1) < 1.04;
153  
154 sub new {
155 my $class = shift;
156 my $name = shift;
157 my %daemon_options = @_;
158  
159 # Forks (workers)
160 my $forks = tv2int8($daemon_options{forks} || DAEMONFORKS);
161 $daemon_options{forks} = $forks < 2 ? 2 : $forks;
162  
163 my $self = $class->SUPER::new($name, %daemon_options);
164  
165 # Create general properties
166 $self->{store} = undef; # Store instance
167 $self->{notifier} = undef; # Notifier instance
168 $self->{checker} = undef; # Checker instance
169 #print _explain($self->ctk->config);
170  
171 return $self;
172 }
173  
174 sub init {
175 my $self = shift;
176 my $ctk = $self->get_ctk;
177 my $logger = $self->logger; # Logger realy is exists?
178 #$logger->log_debug(">> Init handler");
179  
180 # Check logger
181 unless ($logger && $logger->status) {
182 printf STDERR "Can't init logger: %s\n", $logger ? $logger->error : "no logger object";
183 return;
184 }
185  
186 # Check configuration
187 my $configobj = $ctk->configobj;
188 unless ($configobj->status) {
189 print STDERR length($configobj->error)
190 ? $configobj->error
191 : "Can't load configuration file";
192 return;
193 }
194  
195 #print $self->ctk->datadir, "\n";
196 #return $self->interrupt(1);
197  
198 return 1;
199 }
200 sub down {
201 my $self = shift;
202 my $logger = $self->logger; # Logger realy is exists?
203 #$logger->log_info(">> Down handler");
204  
205 # Cleaning DB
206 my $expire = getExpireOffset(lvalue($self->ctk->config("expires"))
207 || lvalue($self->ctk->config("expire")) || EXPIRES);
208 $self->store->clean(period => $expire) or do {
209 $logger->log_error("Can't cleanup database: %s", $self->store->error)
210 if $self->store->error;
211 };
212  
213 return 1;
214 }
215 sub cleanup {
216 my $self = shift;
217 my $logger = $self->logger; # Logger realy is exists?
218  
219 #$logger->log_info(">> CleanUp handler");
220  
221 return 1;
222 }
223 sub reload {
224 my $self = shift;
225 my $logger = $self->logger;
226  
227 # Check configuration
228 my $configobj = $self->ctk->configobj;
229 unless ($configobj->reload->status) {
230 print STDERR length($configobj->error)
231 ? $configobj->error
232 : "Can't reload configuration file";
233 return $self->interrupt(1);
234 }
235  
236 #$logger->log_info(">> Reload handler");
237 return 1;
238 }
239 sub run {
240 my $self = shift;
241 my $ctk = $self->get_ctk;
242 my $logger = $self->logger;
243 my $quit_program = AnyEvent->condvar;
244 return 1 unless $self->ok;
245 #$logger->log_info(">> Run handler");
246  
247 # CTK config
248 my $config = $ctk->config;
249  
250 # Get checkits and allocation by workers
251 my @checkits = getCheckitByName($ctk->config("checkit"));
252 my $noc = scalar(@checkits);
253 unless ($noc) {
254 $logger->log_error("No enabled <Checkit> configuration section found");
255 return 0;
256 }
257 my @checkits_parted = (_allocate($self->{forkers}, [(sort {$a->{name} cmp $b->{name}} @checkits)]));
258 my $alloc = $checkits_parted[$self->{workerident} - 1];
259  
260 # Store
261 my $db_file = File::Spec->catfile($ctk->datadir, App::MonM::Store::DB_FILENAME());
262 my $store_conf = $ctk->config("store") || $ctk->config('dbi') || {file => $db_file};
263 $store_conf = {file => $db_file} unless is_hash($store_conf);
264 my %store_args = %$store_conf;
265 $store_args{file} = $db_file unless ($store_args{file} || $store_args{dsn});
266 my $store = App::MonM::Store->new(%store_args);
267 if ($store->error) {
268 $logger->log_error($store->error);
269 return 0;
270 }
271 $self->{store} = $store;
272  
273 # Notifier object init
274 my %nargs = (config => $ctk->configobj);
275 $self->{notifier} = $NOTIFIER_LOADED && lvalue($ctk->config("usemonotifier"))
276 ? App::MonM::Notifier->new(%nargs)
277 : App::MonM::QNotifier->new(%nargs);
278  
279 # Create Checkit object
280 $self->{checker} = App::MonM::Checkit->new;
281  
282 # Create process timers
283 my $ctrl = AnyEvent->timer (after => START_DELAY, interval => INTERVAL_CTRL, cb => sub {
284 $quit_program->send(1) unless $self->ok;
285 });
286 my $interval = int(uv2zero(lvalue($ctk->config("interval"))) || INTERVAL_MAIN); # Time interval. 1 op per n sec
287 my $after = (($self->{workerident} - 1) * int($interval / ($self->{forkers} - 1))) || START_DELAY;
288 my $timer = AnyEvent->timer (after => $after, interval => $interval, cb => sub {
289 $quit_program->send(1) unless $self->ok;
290 $self->slave($alloc); # Go!
291 });
292 my $rmnd = AnyEvent->timer (after => INTERVAL_REMIND+START_DELAY, interval => INTERVAL_REMIND, cb => sub {
293 $quit_program->send(1) unless $self->ok;
294 $self->remind() if $self->{workerident} == 1;
295 });
296  
297 # Run!
298 $quit_program->recv;
299  
300 return 1;
301 }
302 sub remind {
303 my $self = shift;
304 return $self->logger->log_error(($self->notifier->error)) unless $self->notifier->remind;
305 return 1;
306 }
307 sub slave {
308 my $self = shift;
309 my $checkits = shift;
310 my $ctk = $self->get_ctk;
311 my $logger = $self->logger;
312 my $worker = $self->{workerident};
313 my $store = $self->store;
314 #$logger->log_info(">> $$ worker=%d", $worker);
315  
316 # Check checkits
317 return 1 unless $checkits && is_array($checkits) && isnt_void($checkits);
318  
319 # Get Checker object
320 my $checker = $self->checker;
321  
322 # Get all records from DB
323 my %all;
324 foreach my $r ($store->getall) { $all{$r->{name}} = $r }
325 if ($store->error) {
326 $logger->log_error($store->error);
327 return 1;
328 }
329  
330 # Start
331 my $curtime = time;
332 foreach my $checkit (@$checkits) {
333 my $result = 1; # Check result
334 my $name = $checkit->{name}; # checkit name
335 my $info = $all{$name} || {}; # data from database
336 my $id = $info->{id} || 0;
337 my $old = $info->{status} || 0;
338 my $got = ($old << 1) & 15;
339 my $pub = $info->{'time'} || 0;
340 my $interval = getTimeOffset(lvalue($checkit, "interval") || 0);
341  
342 # Check interval first
343 if ($interval) {
344 if (($pub + $interval) >= $curtime) {
345 $logger->log_debug("SKIP %s (%s)\n", $name,
346 "Too little time has passed before a next check [delay $interval sec]")
347 if $ctk->verbosemode;
348 next;
349 }
350 }
351  
352 # Check!
353 $result = $checker->check($checkit);
354 $got = setBit($got, 0) if $result; # Set first bit if result is PASSED
355  
356 # Show resulsts
357 if ($ctk->verbosemode) {
358 $logger->log_debug("%s %s (%s >>> %s)\n", $result ? "OK" : "FAIL",
359 $name, $checker->source, $checker->message);
360 $logger->log_error("%s", $checker->error) unless $checker->status;
361 }
362  
363 # Save data to database
364 my %data = (
365 id => $id, # DB record id
366 status => $got, # Result code
367 name => $name, # Checkit name
368 type => $checker->type, # Checkit type
369 result => $result, # Checkit result
370 source => $checker->source, # Source string
371 code => $checker->code, # Checkit code value
372 message => $checker->message, # Checkit message string
373 note => $checker->note, # Checkit note string
374 subject => sprintf("%s: Available %s [%s]", $result ? 'OK' : 'PROBLEM', $name, HOSTNAME), # Subject
375 );
376 my $chst = $id ? $store->set(%data) : $store->add(%data);
377 unless ($chst) {
378 $logger->log_error($store->error) if $store->error;
379 next;
380 }
381  
382 # Triggers and notifications
383 # GOT = [0-0-1-1] = 3 -- OK
384 # GOT = [1-1-0-0] = 12 -- PROBLEM
385 if ($got == 3 or $got == 12) {
386 my @errs;
387 $data{status} = $checker->status; # Checkit status (NO RESULT!!);
388 push @errs, $checker->error if $checker->error; # Checkit error string
389  
390 # Run triggers (FIRST)
391 push @errs, $self->trigger(%data, trigger => array($checkit, "trigger"));
392  
393 # Send message via notifier (SECOND)
394 $self->notify(%data, sendto => array($checkit, "sendto"), errors => \@errs);
395 }
396 }
397  
398 return 1;
399 }
400  
401 sub store {
402 my $self = shift;
403 return $self->{store};
404 }
405 sub notifier {
406 my $self = shift;
407 return $self->{notifier};
408 }
409 sub checker {
410 my $self = shift;
411 return $self->{checker};
412 }
413  
414 sub trigger {
415 my $self = shift;
416 my %args = @_;
417 my $subject = $args{subject};
418 my $message = $args{message} // "";
419 my $source = $args{source} // "";
420 my $triggers = $args{trigger} || [];
421 my $logger = $self->logger;
422 my @errs;
423  
424 # Execute triggers
425 foreach my $trg (@$triggers) {
426 next unless $trg;
427 my $cmd = dformat($trg, {
428 SUBJECT => $subject, SUBJ => $subject, SBJ => $subject,
429 MESSAGE => $message, MSG => $message,
430 SOURCE => $source, SRC => $source,
431 NAME => $args{name} || 'virtual',
432 TYPE => $args{type} // 'http',
433 CODE => $args{code} // '',
434 STATUS => $args{status} ? 'OK' : 'ERROR',
435 RESULT => $args{result} ? 'PASSED' : 'FAILED',
436 NOTE => $args{note} // '',
437 });
438 my $exe_err = '';
439 my $exe_out = execute($cmd, undef, \$exe_err);
440 my $exe_stt = ($? >> 8) ? 0 : 1;
441 if ($exe_stt) {
442 $logger->log_info("# %s", $cmd);
443 } else {
444 $exe_err //= "unknown error"; chomp($exe_err);
445 my $msg = sprintf("Can't execute trigger %s: %s", $cmd, $exe_err);
446 $logger->log_error("%s", $msg);
447 push @errs, $msg;
448 }
449 }
450  
451 return @errs;
452 }
453 sub notify {
454 my $self = shift;
455 my %args = @_;
456 my $name = $args{name} || 'virtual';
457 my $errs = $args{errors};
458 my $logger = $self->logger;
459 my @errors;
460 push @errors, @$errs if is_array($errs);
461  
462 # Header
463 my @header;
464 push @header, (
465 ["Checkit", $name], # Checkit name
466 ["Type", $args{type} || 'http'], # Checkit type
467 ["Result", $args{result} ? 'PASSED' : 'FAILED'], # Checkit result
468 ["Source", $args{source} || "UNKNOWN"], # Source string
469 ["Status", $args{status} ? 'OK' : 'ERROR'], # Checkit status (NO RESULT!!);
470 ["Code", $args{code} // "UNKNOWN"], # Checkit code value
471 ["Note", $args{note} // "No comments"], # Checkit note string
472 ["Message", $args{message} // ""], # Checkit message string
473 );
474  
475 # Report
476 my $report = App::MonM::Report->new(name => $name, configfile => $self->ctk->configfile);
477 $report->title($args{result} ? "checking report" : "error report");
478 $report->common(@header); # Common information
479 $report->summary($args{result} ? "All checks successful" : "Errors occurred while checking"); # Summary
480 $report->errors(@errors) if @errors; # List of occurred errors
481 $report->footer($self->ctk->tms);
482  
483 # Send
484 my $notify_status = $self->notifier->notify(
485 to => $args{sendto} || [],
486 subject => $args{subject},
487 message => $report->as_string,
488 before => sub {
489 my $this = shift; # App::MonM::QNotifier object (this)
490 my $message = shift; # App::MonM::Message object
491  
492 # Check internal errors
493 $logger->log_error("%s", $this->error) if $this->error;
494  
495 return 1;
496 },
497 after => sub {
498 my $this = shift; # App::MonM::QNotifier object (this)
499 my $message = shift; # App::MonM::Message object
500 my $sent = shift; # Status of sending
501  
502 # Check internal errors
503 $logger->log_error("%s", $this->error) if $this->error;
504  
505 # Check sending status
506 if ($sent) {
507 my $msg = $this->channel->error
508 ? sprintf("Message was not sent to %s: %s", $message->recipient, $this->channel->error)
509 : sprintf("Message has been sent to %s", $message->recipient);
510 if ($this->channel->error) {
511 $logger->log_error("%s", $msg);
512 } else {
513 $logger->log_info("%s", $msg);
514 }
515 } else {
516 my $err = sprintf("Message was not sent to %s: %s", $message->recipient, $this->channel->error || "unknown error");
517 $logger->log_error("%s", $err);
518 }
519  
520 return 1;
521 },
522 );
523 $logger->log_error($self->notifier->error) unless $notify_status;
524  
525 return 1;
526 }
527  
528 # Allocate chekits
529 sub _allocate { # (3, [qw/a1 a2 a3 a4 a5 a6 a7/]) -> ([a1, a4, a7], [a2, a5], [a3, a6])
530 my $forks = shift || 0;
531 my $_acts = shift || [];
532 my @acts = @$_acts;
533 my @res = ();
534 while ($forks && @acts) {
535 foreach my $f (0..($forks-1)) {
536 $res[$f] = [] unless exists $res[$f];
537 my $nxt = shift(@acts);
538 last unless defined $nxt;
539 push @{$res[$f]}, $nxt;
540 }
541 }
542 return @res;
543 }
544  
545 1;
546  
547 __END__