script/webmon.pl untested

filter: Statementstmt 0.0% 0 / 185 Branchbran 0.0% 0 / 44 Conditioncond 0.0% 0 / 30 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 302 CC 10 SCAR 29.3
CC
10
Cov
0%
read_configuration_recursive
56.0
notify
12.0
log_notification
6.0
CRAP 18.6
1 #!/usr/local/bin/perl
2  
3 eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
4 if 0; # not running under some shell
5 ########################################################################
6 # Filename: webmon.pl - Version 1.0 #
7 # Author: Yaron Kahanovitch <yaron at kahanovitch dor com> #
8 # #
9 # Usage: webmon.pl --conf=filename #
10 # #
11 # Scans a list of web adderesses and compares them with pre-cached #
12 # pages version. If a change is detected, a mail notification is #
13 # being sent. webmon.pl use WWW::Monitor as the primary engine to #
14 # perform monitoring. Mail is being sent via MIME::Lite, and #
15 # Scheduling is being done by using Schedule::Cron mechanism #
16 # #
17 # Copyright 2007 Yaron Kahanovitch, all rights reserved. This #
18 # program is free software; you can redistribute it and/or modify it #
19 # under the same terms as Perl itself. #
20 ########################################################################
21  
22 use Getopt::Long;
23 use LWP::UserAgent;;
24 use WWW::Monitor;
25 use Schedule::Cron;
26 use Cache::File;
27 use Carp;
28 use Text::WordDiff;
29  
30 $VERSION = 1.21;
31  
32 $CONFIG = '/etc/webmon.conf';
33 $LOGPATH = "";
34 $LAST_ERROR = "";
35 $FROM="";
36 $SUBJECT="";
37 %RECIPIENTS = ();
38  
39 GetOptions ( 'help' => \&HELP_MESSAGE,
40 'version' => sub { VERSION_MESSAGE();exit(0);},
41 'conf=s' => \$CONFIG) or HELP_MESSAGE();
42  
43 #HELP_MESSAGE() unless $ARGV[0];
44  
45 croak "Given configuration file, $CONFIG, cannot be located" unless (-f $CONFIG);
46 my $conf = read_configuration($CONFIG) or croak "Cannot read configuration file $CONFIG. $LAST_ERROR";
47 #dump_conf($conf);
48 unless (exists ($conf->{query})) { warn "No queries given ";exit(0);}
49  
50 #Setting up mail fileds.
51 $FROM = $conf->{from}[-1] if (exists $conf->{from});
52 $SUBJECT=$conf->{subject}[-1] if (exists $conf->{subject});
53  
54 #Setting text formatting foelds
55 $RIGHT_MARGIN=120; #DEfault value
56 $RIGHT_MARGIN=$conf->{rightmargin}[-1] if(exists($conf->{rightmargin}));
57 $LEFT_MARGIN=0;#Deafault
58 $LEFT_MARGIN=$conf->{leftmargin}[-1] if(exists($conf->{leftmargin}));
59  
60 #Preparing Log directory.
61 $LOG_NOTIFICATIONS="";
62 $LOG_NOTIFICATIONS=$conf->{log_notification} if (exists($conf->{log_notification}));
63 $LOGPATH = $conf->{log_mail_dir}[-1] if (exists $conf->{log_mail_dir});
64 if ($LOGPATH and ! -d $LOGPATH and !mkdir($LOGPATH)) {
65 print STDERR "Cannot Create directory $LOGPATH.$! \n";
66 }
67  
68 #Setting up cache object.
69 my $cache_root = '/var/cache/monitor';
70  
71 #Initialize Cron object
72 my $cron = new Schedule::Cron(sub { return 1;});
73  
74 if (exists $conf->{cache_root} and
75 scalar(@{$conf->{cache_root}})) {
76 $cache_root = $conf->{cache_root}[-1];
77 }
78  
79  
80 #Setting up cache object
81 if (!-d $cache_root and !mkdir($cache_root)) {
82 print STDERR "Cannot create directory $cache_root \n";
83 exit 255;
84 }
85 $cache = Cache::File->new( cache_root => $cache_root);
86  
87 #Setting up queries
88 my $indx = 0;
89 foreach my $query (@{$conf->{query}}) {
90 ++$indx;
91 foreach my $reserved_word ("url","sampling_rate") {
92 unless (exists $query->{$reserved_word}) {
93 print STDERR "Missing $reserved_word in query $indx\n";
94 exit (255);
95 }
96 }
97 #Initializing WWW::Monitor object
98  
99 my $mon = WWW::Monitor->new('MAIL_CALLBACK'=>\&notify,'CACHE'=>$cache);
100 foreach my $url (@{$query->{url}}) {
101 my $task = $mon->watch("$url");
102 log_notification("Watching ",$url);
103 $RECIPIENTS{$task}=$query->{mailto};
104 }
105 foreach my $cron_samp (@{$query->{sampling_rate}}) {
106 log_notification ("sampling_rate = ",$cron_samp);
107 $cron->add_entry($cron_samp,\&run_query,$mon);
108 # run_query($mon);
109 }
110 }
111  
112 log_notification ("Started\n********\n");
113  
114 $cron->run();
115  
116  
117 sub run_query {
118 my $mon = shift;
119 # print "Getting started\n";
120 log_notification("Testing: ",join("\n",$mon->targets));
121 $mon->run or log_notification("Query ended with error",$mon->errors);
122 return 1;
123 }
124  
125  
126  
127 #Basic parser. Configuration should have the format key=value. Nesting can be achieved by specifing sub parts. For example query start....end specify sub part names query.
128 sub read_configuration {
129 my $q_file = shift;
130 open QFILE,"<$q_file" or do{ report_error("Cannot open $q_file for read.$!"); return 0;};
131 my $res = {};
132 my $lineNum = 0;
133 read_configuration_recursive(\*QFILE,$res,\$lineNum) or return 0;
134 close QFILE;
135 return $res;
136 }
137  
138  
139 sub read_configuration_recursive {
140 my $qfile = shift;
141 my $res = shift;
142 my $lineNum = shift;
143 while (<$qfile>) {
144 ++$$lineNum;
145 chomp;
146 $_ =~ s/#.*//;
147 $_ =~ s/^\s+//;
148 next if ($_ eq "");
149 return 1 if ($_ eq "end");
150 my @fields = split("=",$_);
151 if (scalar(@fields) >= 2) {
152 my $a1 = $fields[0];
153 my $a2 = join("=",@fields[1..$#fields]);
154 $res->{$a1} = [] unless (exists ($res->{$a1}));
155 push @{$res->{$a1}},$a2;
156 next;
157 }
158 if (/(\S+)\s+start/) {
159 my $key = $1;
160 my $inner = {};
161 $res->{$key} = [] unless(exists $res->{$key});
162 push @{$res->{$key}},$inner;
163 read_configuration_recursive($qfile,$inner,$lineNum) or return 0;
164 next;
165 }
166 report_error("parse error at line $$lineNum ($_)");return 0;
167 }
168 return 1;
169 }
170  
171 sub VERSION_MESSAGE {
172 print "$0 $VERSION (C) 2007 Yaron Kahanovitch.\n";
173 }
174  
175 sub HELP_MESSAGE {
176 VERSION_MESSAGE();
177 print <<EOT;
178 usage: $0 --conf=<configuration file name>
179 options:
180 --conf=file Configuration file name. Deafault $CONFIG
181 EOT
182 exit 0;
183 }
184  
185 sub report_error {
186 $LAST_ERROR = @_;
187 return 1;
188 }
189  
190 #mail notification callback
191 sub notify {
192 my ($url,$task) =@_;
193 my $text = "";
194  
195 $text .= "<br>$url has changed since last visited</br>";
196 $text .= "<br>This url was visited in ";
197 $text .= $task->new_version_time_stamp();
198 $text .= "</br><br>Previously the site was visited in ";
199 $text .= $task->old_version_time_stamp();
200 $text .= "</br>";
201
202 # my $mime_type = "";
203  
204 my $missing_parts = $task->missing_parts();
205 while (my ($missing_url,$missing_data) = each %$missing_parts) {
206 $text .= "<br><p>The following part is missing:$missing_url - </p></br>";
207 $text .= $task->format_html($missing_data,$LEFT_MARGIN,$RIGHT_MARGIN);
208 $text .= <br/>;
209 }
210  
211 my $added_parts = $task->added_parts();
212 while (my ($added_url,$added_data) = each %$added_data) {
213 $text .= "<br><p>New part found: $added_url</p></br>";
214 $text.= $task->format_html($added_data,$LEFT_MARGIN,$RIGHT_MARGIN);
215 $text .=<br/>
216 }
217
218 my $ind = 0;
219 foreach my $changed_url ($task->changed_parts()){
220 $ind++;
221 my ($old,$new) = $task->get_old_new_pair($changed_url);
222 # $mime_type = $new->header('Content-Type') unless ($mime_type);
223
224 my $old_content = ${$task->format_html($old,$LEFT_MARGIN,$RIGHT_MARGIN)};
225 my $new_content = ${$task->format_html($new,$LEFT_MARGIN,$RIGHT_MARGIN)};
226 if ($task->is_html($new)) {
227 my $this_diff = word_diff (\$old_content, \$new_content, { STYLE => 'HTML' });
228 $this_diff =~ s%\n%<br/>%g;
229 $text .= $this_diff;
230 } else {
231 $text .= "<br> $changed_url has changed</br>";
232 }
233 }
234
235 foreach my $recipient (@{$RECIPIENTS{$task}}) {
236 my $mail_obj = LWP::UserAgent->new;
237 $mail_obj->agent("MyApp/0.1 ");
238 my $req = HTTP::Request->new(POST => 'mailto:'.$recipient);
239 $req->header(Subject=>$SUBJECT);
240 $req->header(From=>$FROM);
241 $req->content_type('text/html');
242 $req->content( "<br>For details visit <a href=\"$url\">$url</a></br>$text");
243 my $res = $mail_obj->request($req);
244 if ($res->is_success) {
245 log_notification($res->content);
246 }
247 else {
248 log_notification("Fail to send mail to $recipient.$res->status_line");
249 }
250 }
251 return 1;
252 }
253  
254 #Simple log sub.
255 sub log_notification {
256 return 1 unless ($LOGPATH);
257 my @message = @_;
258 open HIST,">>$LOGPATH/www-monitor-log" or print STDERR "Cannot open log file.$! \n";
259 my $message_frmt = join("",(HTTP::Date::time2str(time()),"==>",@message,"\n"));
260 print HIST $message_frmt,"\n*******************************************************\n";
261 close HIST;
262 }
263
264 sub dump_conf {
265 my $conf = shift;
266 while (my ($key,$val) = each %$conf) {
267 print "$key ==> $val \n";
268 }
269 return 1;
270 }
271  
272 __END__