| 1 | package Monitoring::Spooler::Cmd::SendingCommand; | ||
| 2 | $Monitoring::Spooler::Cmd::SendingCommand::VERSION = '0.05'; | ||
| 3 | BEGIN { | ||
| 4 | $Monitoring::Spooler::Cmd::SendingCommand::AUTHORITY = 'cpan:TEX'; | ||
| 5 | } | ||
| 6 | # ABSTRACT: base class for any sending command | ||
| 7 | |||
| 8 | use 5.010_000; | ||
| 9 | use mro 'c3'; | ||
| 10 | use feature ':5.10'; | ||
| 11 | |||
| 12 | use Moose; | ||
| 13 | use namespace::autoclean; | ||
| 14 | |||
| 15 | # use IO::Handle; | ||
| 16 | # use autodie; | ||
| 17 | # use MooseX::Params::Validate; | ||
| 18 | # use Carp; | ||
| 19 | # use English qw( -no_match_vars ); | ||
| 20 | use Try::Tiny; | ||
| 21 | use Module::Pluggable::Object; | ||
| 22 | use Proc::ProcessTable; | ||
| 23 | use LWP::UserAgent; | ||
| 24 | use URI::Escape; | ||
| 25 | |||
| 26 | # extends ... | ||
| 27 | extends 'Monitoring::Spooler::Cmd::Command'; | ||
| 28 | # has ... | ||
| 29 | has '_finder' => ( | ||
| 30 | 'is' => 'rw', | ||
| 31 | 'isa' => 'Module::Pluggable::Object', | ||
| 32 | 'lazy' => 1, | ||
| 33 | 'builder' => '_init_finder', | ||
| 34 | 'accessor' => 'finder', | ||
| 35 | ); | ||
| 36 | |||
| 37 | has '_transports' => ( | ||
| 38 | 'is' => 'rw', | ||
| 39 | 'isa' => 'ArrayRef[Monitoring::Spooler::Transport]', | ||
| 40 | 'lazy' => 1, | ||
| 41 | 'builder' => '_init_transports', | ||
| 42 | 'accessor' => 'transports', | ||
| 43 | ); | ||
| 44 | |||
| 45 | has '_pid' => ( | ||
| 46 | 'is' => 'ro', | ||
| 47 | 'isa' => 'Int', | ||
| 48 | 'lazy' => 1, | ||
| 49 | 'builder' => '_init_pid', | ||
| 50 | 'reader' => 'pid', | ||
| 51 | ); | ||
| 52 | |||
| 53 | has '_fallback_url' => ( | ||
| 54 | 'is' => 'rw', | ||
| 55 | 'isa' => 'Str', | ||
| 56 | 'lazy' => 1, | ||
| 57 | 'builder' => '_init_fallback_url', | ||
| 58 | 'accessor' => 'fallback_url', | ||
| 59 | ); | ||
| 60 | |||
| 61 | has '_ua' => ( | ||
| 62 | 'is' => 'rw', | ||
| 63 | 'isa' => 'LWP::UserAgent', | ||
| 64 | 'lazy' => 1, | ||
| 65 | 'builder' => '_init_ua', | ||
| 66 | ); | ||
| 67 | # with ... | ||
| 68 | # initializers ... | ||
| 69 | sub _init_pid { | ||
| 70 | my $self = shift; | ||
| 71 | |||
| 72 | # Why is _init_pid here and not in our superclass (Command)? | ||
| 73 | # Well, because the 'other' commands may very well run in parallel. | ||
| 74 | # Since they only interact w/ the DB and SQLite should handle | ||
| 75 | # concurrent accesses there is no harm. But any SendingCommand | ||
| 76 | # interacts w/ the 'outside' where we don't have the benefit | ||
| 77 | # of a single point of access (like, say sqlite) or ACID | ||
| 78 | # transactions we need to make sur only one proc of a given type runs at | ||
| 79 | # a time. | ||
| 80 | |||
| 81 | # first we clean up any pids which aren't valid anymore ... | ||
| 82 | $self->_clean_procs(); | ||
| 83 | |||
| 84 | # bail out if there is another one of our type running | ||
| 85 | my $sql = 'SELECT COUNT(*) FROM running_procs WHERE type = ? AND name = ?'; | ||
| 86 | my $sth = $self->dbh()->prepare($sql); | ||
| 87 | $sth->execute($self->_media_type(),$0); | ||
| 88 | my $count = $sth->fetchrow_array(); | ||
| 89 | |||
| 90 | die("Already running!") if $count > 0; | ||
| 91 | |||
| 92 | my $pid = $$; | ||
| 93 | |||
| 94 | $sql = 'INSERT INTO running_procs (pid,type,name) VALUES(?,?,?)'; | ||
| 95 | $sth = $self->dbh()->prepare($sql); | ||
| 96 | $sth->execute($pid,$self->_media_type(),$0); | ||
| 97 | |||
| 98 | return $pid; | ||
| 99 | } | ||
| 100 | |||
| 101 | sub _init_finder { | ||
| 102 | my $self = shift; | ||
| 103 | |||
| 104 | # The finder is the class that finds our available Transports (pronounce: Plugins) | ||
| 105 | my $Finder = Module::Pluggable::Object::->new('search_path' => 'Monitoring::Spooler::Transport'); | ||
| 106 | |||
| 107 | return $Finder; | ||
| 108 | } | ||
| 109 | |||
| 110 | sub _init_fallback_url { | ||
| 111 | my $self = shift; | ||
| 112 | |||
| 113 | return $self->config()->get('Monitoring::Spooler::FallbackUrl', { Default => '' }); | ||
| 114 | } | ||
| 115 | |||
| 116 | sub _init_ua { | ||
| 117 | my $self = shift; | ||
| 118 | |||
| 119 | my $UA = LWP::UserAgent::->new(); | ||
| 120 | $UA->agent('Monitoring::Spooler/0.11'); | ||
| 121 | |||
| 122 | return $UA; | ||
| 123 | } | ||
| 124 | |||
| 125 | sub _init_transports { | ||
| 126 | my $self = shift; | ||
| 127 | |||
| 128 | # Allow the transports to be sorted by prio in the config with the Priority | ||
| 129 | # key in each transport section. Why priorities? They allow us to load | ||
| 130 | # multiple transports for each media type and try each one in a well defined | ||
| 131 | # (as long as you don't use any single priority twice) order. | ||
| 132 | # If one fails mysteriously we can just go on to the next. Nice, eh'? | ||
| 133 | my $order_ref = {}; | ||
| 134 | |||
| 135 | foreach my $plugin_name ($self->finder()->plugins()) { | ||
| 136 | ## no critic (ProhibitStringyEval) | ||
| 137 | my $eval_status = eval "require $plugin_name;"; | ||
| 138 | ## use critic | ||
| 139 | if(!$eval_status) { | ||
| 140 | $self->logger()->log( message => 'Failed to require '.$plugin_name.': '.$@, level => 'warning', ); | ||
| 141 | next; | ||
| 142 | } | ||
| 143 | my $arg_ref = $self->config()->get($plugin_name); | ||
| 144 | $arg_ref->{'logger'} = $self->logger(); | ||
| 145 | $arg_ref->{'config'} = $self->config(); | ||
| 146 | $arg_ref->{'dbh'} = $self->dbh(); | ||
| 147 | if($arg_ref->{'disabled'}) { | ||
| 148 | $self->logger()->log( message => 'Skipping disabled transport: '.$plugin_name, level => 'debug', ); | ||
| 149 | next; | ||
| 150 | } | ||
| 151 | try { | ||
| 152 | my $Transport = $plugin_name->new($arg_ref); | ||
| 153 | # skip any transport plugin that does not provide the media type | ||
| 154 | # we want/need. Since this uses an instance method we have to | ||
| 155 | # instantiate the class first. Well ... we _could_ use a global | ||
| 156 | # variable which we could access right after the require but that | ||
| 157 | # would mean we had to use a global variable. Not on my lawn ... | ||
| 158 | die("Media-Type not supported by $plugin_name\n") | ||
| 159 | unless $Transport->provides($self->_media_type()); | ||
| 160 | # use a default prio of 10 | ||
| 161 | my $prio = $arg_ref->{'priority'} || 10; | ||
| 162 | push(@{$order_ref->{$prio}},$Transport); | ||
| 163 | } catch { | ||
| 164 | $self->logger()->log( message => 'Failed to initialize plugin '.$plugin_name.' w/ error: '.$_, level => 'warning', ); | ||
| 165 | }; | ||
| 166 | } | ||
| 167 | |||
| 168 | my @transports = (); | ||
| 169 | |||
| 170 | # this basically merges the pre-sorted sub-arrays (which, if you follow | ||
| 171 | # my advice, should each contain only one element ... but we must | ||
| 172 | # plan for the unexptected, of course) | ||
| 173 | foreach my $prio (sort keys %$order_ref) { | ||
| 174 | push(@transports,@{$order_ref->{$prio}}); | ||
| 175 | } | ||
| 176 | |||
| 177 | # call fallback url if there aren't any working transports | ||
| 178 | if(scalar(@transports) < 1 && $self->fallback_url()) { | ||
| 179 | $self->_fallback_notify('Failed to initialize at least one transport'); | ||
| 180 | } | ||
| 181 | |||
| 182 | return \@transports; | ||
| 183 | } | ||
| 184 | |||
| 185 | sub BUILD { | ||
| 186 | my $self = shift; | ||
| 187 | |||
| 188 | # just make sure our pid is in the pid list | ||
| 189 | # a build is nice and handy by itself | ||
| 190 | # but only BUILD will be called ALL THE WAY UP by Moose | ||
| 191 | # on instantiation. This is usually not what you want but | ||
| 192 | # here it should be perfect. | ||
| 193 | $self->pid(); | ||
| 194 | |||
| 195 | return 1; | ||
| 196 | } | ||
| 197 | |||
| 198 | sub DEMOLISH { | ||
| 199 | my $self = shift; | ||
| 200 | |||
| 201 | # this should remove this procs pid from the pid list | ||
| 202 | my $sql = 'DELETE FROM running_procs WHERE pid = ?'; | ||
| 203 | my $sth = $self->dbh()->prepare($sql); | ||
| 204 | $sth->execute($self->pid()); | ||
| 205 | |||
| 206 | return; | ||
| 207 | } | ||
| 208 | |||
| 209 | # your code here ... | ||
| 210 | sub _fallback_notify { | ||
| 211 | my $self = shift; | ||
| 212 | my $message = shift; | ||
| 213 | |||
| 214 | $message = 'Internal Monitoring::Spooler error' unless $message; | ||
| 215 | |||
| 216 | if(!$self->fallback_url()) { | ||
| 217 | $self->logger()->log( message => 'No fallback url defined. Can not send message: '.$message, level => 'error', ); | ||
| 218 | return; | ||
| 219 | } | ||
| 220 | |||
| 221 | my $req = HTTP::Request::->new( GET => $self->fallback_url().uri_escape($message), ); | ||
| 222 | my $res = $self->_ua()->request($req); | ||
| 223 | |||
| 224 | if($res->is_success()) { | ||
| 225 | $self->logger()->log( message => 'Sent '.$message, level => 'debug', ); | ||
| 226 | return 1; | ||
| 227 | } else { | ||
| 228 | my $errstr = $res->content(); | ||
| 229 | if($self->responses()->{$errstr}) { | ||
| 230 | $errstr .= ' - '.$self->responses()->{$errstr}; | ||
| 231 | } | ||
| 232 | $self->logger()->log( message => 'Failed to send '.$message.'. Error: '.$errstr, level => 'debug', ); | ||
| 233 | return; | ||
| 234 | } | ||
| 235 | } | ||
| 236 | |||
| 237 | sub _clean_procs { | ||
| 238 | my $self = shift; | ||
| 239 | |||
| 240 | # this is an ugly method that removes any orphaned pids from the | ||
| 241 | # pid list. this is annoying and expensive but we just can not rely | ||
| 242 | # on DEMOLISH above to work properly always. Experience show | ||
| 243 | # that it _will_ fail (at least if we don't use a method like this one). | ||
| 244 | |||
| 245 | my $PT = Proc::ProcessTable::->new(); | ||
| 246 | my $procs = {}; | ||
| 247 | foreach my $proc (@{$PT->table()}) { | ||
| 248 | $procs->{$proc->pid()} = $proc->cmndline(); | ||
| 249 | } | ||
| 250 | $PT = undef; | ||
| 251 | |||
| 252 | my $sql = 'SELECT pid,name FROM running_procs WHERE type = ?'; | ||
| 253 | my $sth = $self->dbh()->prepare($sql); | ||
| 254 | $sth->execute($self->_media_type()); | ||
| 255 | $sql = 'DELETE FROM running_procs WHERE pid = ?'; | ||
| 256 | my $sth_del = $self->dbh()->prepare($sql); | ||
| 257 | while(my ($pid, $name) = $sth->fetchrow_array()) { | ||
| 258 | if(!$procs->{$pid} || $procs->{$pid} !~ m/\Q$name\E/i) { | ||
| 259 | $sth_del->execute($pid); | ||
| 260 | } | ||
| 261 | } | ||
| 262 | $sth_del->finish(); | ||
| 263 | $sth->finish(); | ||
| 264 | |||
| 265 | return 1; | ||
| 266 | } | ||
| 267 | |||
| 268 | sub _fetch_waiting_messages { | ||
| 269 | my $self = shift; | ||
| 270 | |||
| 271 | # get messages waiting in queue | ||
| 272 | my $sql = 'SELECT id,group_id,message,ts,event,trigger_id FROM msg_queue WHERE type = ?'; | ||
| 273 | my $sth = $self->dbh()->prepare($sql); | ||
| 274 | if(!$sth) { | ||
| 275 | $self->logger()->log( message => 'Could not prepare SQL '.$sql.' due to error: '.$self->dbh()->errstr, level => 'warning', ); | ||
| 276 | return; | ||
| 277 | } | ||
| 278 | if(!$sth->execute($self->_media_type())) { | ||
| 279 | $self->logger()->log( message => 'Could not execute SQL '.$sql.' due to error: '.$sth->errstr, level => 'warning', ); | ||
| 280 | return; | ||
| 281 | } | ||
| 282 | # keep one message queue per group | ||
| 283 | my $msg_ref = {}; | ||
| 284 | while(my ($id, $group_id, $message, $ts, $event, $trigger_id) = $sth->fetchrow_array()) { | ||
| 285 | # don't even think about handling negating triggers here. | ||
| 286 | # where do you think the negated one will get deleted? | ||
| 287 | push(@{$msg_ref->{$group_id}}, { | ||
| 288 | 'id' => $id, | ||
| 289 | 'msg' => $message, | ||
| 290 | 'ts' => $ts, | ||
| 291 | 'event' => $event, | ||
| 292 | 'trigger_id' => $trigger_id, | ||
| 293 | }); | ||
| 294 | } | ||
| 295 | $sth->finish(); | ||
| 296 | |||
| 297 | return $msg_ref; | ||
| 298 | } | ||
| 299 | |||
| 300 | sub execute { | ||
| 301 | my $self = shift; | ||
| 302 | |||
| 303 | # get messages waiting in queue | ||
| 304 | my $msg_ref = $self->_fetch_waiting_messages(); | ||
| 305 | |||
| 306 | # prepare stmt to fetch notifcation interval for this group from db | ||
| 307 | my $sql = "SELECT notify_from,notify_to FROM notify_interval WHERE group_id = ? AND type = ?"; | ||
| 308 | my $sth_ni = $self->dbh()->prepare($sql); | ||
| 309 | if(!$sth_ni) { | ||
| 310 | $self->logger()->log( message => 'Could not prepare SQL '.$sql.' due to error: '.$self->dbh()->errstr, level => 'warning', ); | ||
| 311 | return; | ||
| 312 | } | ||
| 313 | |||
| 314 | my $msgs_sent = 0; | ||
| 315 | |||
| 316 | # process each group | ||
| 317 | foreach my $group_id (keys %$msg_ref) { | ||
| 318 | |||
| 319 | # skip this group if there are no messages waiting for it, | ||
| 320 | # shouldn't happen but what does Postel's law teach us? Right: | ||
| 321 | # Be conservative in what you send but liberal in what you accept! | ||
| 322 | next unless scalar(@{$msg_ref->{$group_id}}); | ||
| 323 | |||
| 324 | # skip this group if we're not inside the valid notification interval | ||
| 325 | if(!$sth_ni->execute($group_id,$self->_media_type())) { | ||
| 326 | $self->logger()->log( message => 'Could not execute statement: '.$sth_ni->errstr, level => 'warning', ); | ||
| 327 | next; | ||
| 328 | } | ||
| 329 | # since SQLite has no dedicated time datatype we use the rather ugly | ||
| 330 | # but nonetheless working string notation of HHMM (w/ leading zeros if applicable) | ||
| 331 | my ($notify_from, $notify_to) = $sth_ni->fetchrow_array(); | ||
| 332 | my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); | ||
| 333 | my $nowstr = sprintf("%02d%02d", $hour, $min); | ||
| 334 | if( | ||
| 335 | $notify_from && $notify_to # if the group has no interval set we will notify 24/7 | ||
| 336 | && $notify_from ne $notify_to # if start and end of interval are the same we will notfiy 24/7 | ||
| 337 | && ($nowstr lt $notify_from || $nowstr gt $notify_to ) # if it's too early or too late we will skip this group for now | ||
| 338 | ) { | ||
| 339 | $self->logger()->log( message => 'Not within valid notification interval for group '.$group_id.' - from: '.$notify_from.' - to: '.$notify_to.' - now: '.$nowstr, level => 'notice', ); | ||
| 340 | next; | ||
| 341 | } | ||
| 342 | |||
| 343 | # send the message | ||
| 344 | if($self->_prepare_message_and_send($group_id, $msg_ref)) { | ||
| 345 | # if everything went fine we'll clean up | ||
| 346 | $self->_cleanup(1,$group_id,$msg_ref); | ||
| 347 | } else { | ||
| 348 | # the current implementation of _cleanup does nothing | ||
| 349 | # on failure, but maybe future media-types will need to, so | ||
| 350 | # we'll call it with the apt. flag anyway | ||
| 351 | $self->_cleanup(0,$group_id,$msg_ref); | ||
| 352 | $self->logger()->log( message => 'Failed to process messages for group #'.$group_id, level => 'error', ); | ||
| 353 | if($self->fallback_url()) { | ||
| 354 | $self->_fallback_notify('Failed to send messages to group: '.$group_id); | ||
| 355 | } | ||
| 356 | } | ||
| 357 | } | ||
| 358 | |||
| 359 | # delete expired pause entries | ||
| 360 | $sql = 'DELETE FROM paused_groups WHERE until < ?'; | ||
| 361 | my $sth = $self->dbh()->prepexec($sql,time()); # no error handling, this is not essential | ||
| 362 | $sth->finish(); | ||
| 363 | |||
| 364 | return 1; | ||
| 365 | } | ||
| 366 | |||
| 367 | sub _send_with_best_transport { | ||
| 368 | my $self = shift; | ||
| 369 | my $number = shift; | ||
| 370 | my $message = shift; | ||
| 371 | |||
| 372 | # try each defined transport until one suceeds | ||
| 373 | foreach my $transport (@{$self->transports()}) { | ||
| 374 | $self->logger()->log( message => 'Trying to send using transport '.ref($transport), level => 'debug', ); | ||
| 375 | my $result; | ||
| 376 | try { | ||
| 377 | $result = $transport->run($number,$message); | ||
| 378 | } catch { | ||
| 379 | $self->logger()->log( message => 'Failed to send using transport '.ref($transport).' w/ error: '.$_, level => 'notice', ); | ||
| 380 | }; | ||
| 381 | # defined is important, DTMF may return 0 (which is a successful call | ||
| 382 | # but false in perl anyway). | ||
| 383 | # Novice-Wannabe-Coder: "But PHP handles this better, it has TRUE and FALSE!" | ||
| 384 | # Me: "Fu fu fu. Don't get me started about PHP ... | ||
| 385 | # just read http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/" | ||
| 386 | if(defined($result)) { | ||
| 387 | return $result; | ||
| 388 | } else { | ||
| 389 | $self->logger()->log( message => 'Failed to send w/ transport '.ref($transport).', trying next one ...', level => 'notice', ); | ||
| 390 | } | ||
| 391 | } | ||
| 392 | |||
| 393 | return; | ||
| 394 | } | ||
| 395 | |||
| 396 | sub _media_type { | ||
| 397 | # this superclass doesn't support any kind of media-type | ||
| 398 | # this also makes sure this class won't load an transport plugins by itself | ||
| 399 | # (i.e. w/o being subclassed) | ||
| 400 | return; | ||
| 401 | } | ||
| 402 | |||
| 403 | no Moose; | ||
| 404 | __PACKAGE__->meta->make_immutable; | ||
| 405 | |||
| 406 | 1; | ||
| 407 | |||
| 408 | __END__ |