File/tail.pm untested

filter: Statementstmt 0.0% 0 / 153 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 5 MC/DCmcdc 0.0% 0 / 3 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 241 CC 21 SCAR 34.3
CC
21
Cov
0%
_init
90.0
_file_timer
42.0
_file_read
20.0
CRAP 30.9
1 =head1 NAME
2  
3 Event::File::tail - 'an tail [CB]<-f>' implementation using Event
4  
5 =head1 SYNOPSIS
6  
7 use Event::File;
8 Event::File->tail(
9 file => '/var/log/messages',
10 cb => \&my_read_callback_function
11 );
12 Event::loop;
13  
14 =head1 DESCRIPTION
15  
16 Event::FileTail is an attempt to reproduce the behaviour of the
17 'tail -f' using Event as the backend.
18  
19 The main difference between this module and other modules that tries
20 to implement it is that it leaves room for parallel processing using
21 Event.
22  
23 =cut
24  
25 package Event::File::tail;
26 use strict;
27 use vars qw($VERSION $ID);
28  
29 $VERSION = "0.1.1";
30  
31 #our internal id
32 $ID = 0;
33  
34 #We use Event::File to register
35 'Event::File'->register;
36  
37 #our startup
38 sub new {
39 my $class = shift;
40 my %arg = @_;
41
42 $ID++;
43  
44 # No allocate (at least for now)
45 # my $o = allocate($class, delete $arg{attach_to} || {});
46 my $o={
47 #We keep our "shared" data here
48 _arg => {},
49  
50 #Here goes our internal data stuff
51 _data => {
52  
53 #our internal id
54 id => $ID,
55  
56 #flag to tell if the processing file is the same as before
57 # 0 => no
58 # 1 => yes
59 file_ok => 0,
60  
61 #internal count to keep track of how
62 #many lines have we writen yet
63 #our hardcoded limit is 10
64 file_count => 0,
65  
66 #here we keep the beggining of the file for
67 #footprinting in case the file changes
68 file_footprint => [],
69  
70 #counter to keep track of the file if it gets too quite
71 #(it might be rotated, and we didn't notice)
72 timer_count => 0,
73
74 #Does the file exist?
75 #0 => no
76 #1 => yes
77 file_exist => 0,
78 },
79  
80 #we keep a reference to our internal watchers
81 #remember that we have to undefine it in the
82 #DESTROY sub
83 _watchers => {
84 timer => undef,
85 read => undef,
86 },
87 };
88  
89 bless $o;
90  
91 #Event initioalization stuff
92 # $o->init(\%arg);
93  
94 #our initialization
95 $o->_init(\%arg);
96  
97 $o->_prepare();
98 $o;
99 }
100  
101 =head2 Supported attributes
102  
103 =over
104  
105 =item file
106  
107 file gives the file name to watch, with either a absolute or relative path.
108 The file has to exist during initialization. After it, it can be unlinked and
109 recreated.
110  
111 =item position
112  
113 where to start reading from the file, in bytes. As the file is read, it
114 will be updated with the last position read.
115  
116 =item footprint
117  
118 footprint, if defined, ia an array reference of n elements. Each element correspond
119 to a line from the beggining of the file. If any line does not match in the file,
120 C<position> will be ignored and started in the beggining.
121  
122 =item cb
123  
124 cb is the standard callback. It will receive a code reference that will
125 be called after every line read from the C<file>. The newline from the line
126 will be C<chomp>ed before passed.
127 The Event::File::tail object will be passed as the first argument.
128 The read line will be passed as the second argument.
129  
130 =item timeout
131  
132 A timeout starts to calculate after the file read gets to the end.
133 If a new line is added to the file the timer count is reseted.
134 Its main use is to catch a situation when the C<file> is rotated
135 and it was not catched.
136 The file will be closed and reopened. If the file stills the same
137 it will continue from the place it was before closing it. If the
138 file has really changed, it will start reading it from the beggining.
139 If not specified it defaults to 60s.
140  
141 =item timeout_cb
142  
143 This is the callback to call when a timeout occur.
144 The timeout callback will be only called if the reopened file
145 results in the same file.
146  
147 =item endfile_cb
148  
149 This callback will be called every time when the file read gets
150 to the end. So if you need to do something after reading the
151 file (instead of during each read line).
152  
153 =item desc
154  
155 Description of the watcher.
156  
157 =back
158  
159 =head1 METHODS
160  
161 This are the methods available for use with the tail watcher.
162  
163 =cut
164  
165  
166  
167 #our internal init method
168 sub _init{
169 my ($me, $arg) = @_;
170  
171 die "You must provide a 'file' argument to tail\n" if (!defined($arg->{file}));
172 $me->{_arg}->{file} = $arg->{file};
173  
174 #sets the position
175 $me->{_arg}->{position} = 0;
176 $me->{_arg}->{position} = $arg->{position} if (defined($arg->{position}));
177  
178 #the read callback
179 $me->{_arg}->{cb} = sub {};
180 $me->{_arg}->{cb} = $arg->{cb} if (defined($arg->{cb}));
181  
182 #timeout value
183 $me->{_arg}->{timeout} = 60;
184 $me->{_arg}->{timeout} = $arg->{timeout} if (defined($arg->{timeout}));
185  
186 #the timeout callback
187 $me->{_arg}->{timeout_cb} = sub {};
188 $me->{_arg}->{timeout_cb} = $arg->{timeout_cb} if (defined($arg->{timeout_cb}));
189  
190 #the end of file callback
191 $me->{_arg}->{endfile_cb} = sub{};
192 $me->{_arg}->{endfile_cb} = $arg->{endfile_cb} if (defined($arg->{endfile_cb}));
193  
194 #check for description
195 $me->{_arg}->{desc} = "Event::File->tail watcher. ID: " . $me->{_data}->{id};
196 $me->{_arg}->{desc} = $arg->{desc} if (defined($arg->{desc}));
197  
198 #file foot print
199 $me->{_data}->{file_footprint} = [];
200 $me->{_data}->{file_footprint} = $arg->{footprint} if (defined($arg->{footprint}));
201 }
202  
203 #prepare the real watchers
204 sub _prepare{
205 my ($me) = @_;
206  
207 #opens the file (parked)
208 $me->_open_file(1);
209  
210 #checks wether the faile still the same
211 $me->_file_check_sanity();
212  
213 #adjusts the file
214 $me->{fd}->seek($me->{_arg}->{position}, 0);
215  
216 # The helper timer
217 $me->{_watchers}->{timer} = Event->timer(
218 cb => [$me, '_file_timer'],
219 desc => 'helper watcher for Event::File->tail ID:' . $me->{_data}->{id},
220 interval => 1,
221 prio => 6,
222 parked => 1,
223 );
224  
225 #now we start the read timer
226 $me->{_watchers}->{read}->start;
227 }
228  
229 #this is the timer callback
230 sub _file_read{
231 my ($me, $event)=@_;
232 my ($position, $handler);
233  
234 $handler = $event->w->fd;
235  
236 #There is nothing to read in the file
237 if (eof($handler)){
238  
239 #saves the file position
240 #Attention:
241 #if using sys{read,write,seek} family,
242 #would have to use 'sysseek($handler, 0, 1)' instead of tell
243 $position = tell($handler);
244  
245 #if the file has changed
246 if ($me->{_arg}->{position} != $position){
247  
248 $me->{_arg}->{position} = $position;
249
250 #reset the counter
251 $me->{_data}->{timer_count} = 0;
252  
253 #end of file callback
254 &{$me->{_arg}->{endfile_cb}}($me);
255 }
256  
257 #stops this watcher
258 #there is nothing to read
259 $event->w->stop;
260  
261 #starts the timer
262 $me->{_watchers}->{timer}->again;
263  
264 return;
265 }
266  
267 $_ = <$handler>;
268 chomp;
269  
270  
271 #save the first lines from the from file
272 #right now 10 is a harcoded limit
273 if (( $me->{_data}->{file_count} < 10) && ( $me->{_data}->{file_ok} == 0)){
274 push ( @{$me->{_data}->{file_footprint}}, $_);
275 $me->{_data}->{file_count}++;
276 }
277  
278 #this is the default callback
279 &{$me->{_arg}->{cb}}($me, $_);
280
281 $me->{_data}->{timer_count} = 0;
282 }
283  
284  
285 #######################################
286 # from_file_timer:
287 # timer callback
288 #######################
289 sub _file_timer{
290 my ($me, $event)=@_;
291 my ($pid);
292  
293 #update the counter
294 $me->{_data}->{timer_count}++;
295  
296 #first we check if the file still there
297 if (! -f $me->{_arg}->{file}){
298 #no, the file isn't there (oh oh)
299
300 if ($me->{_data}->{file_exist} == 1){
301 #we probably just got the file being rotate
302  
303 #flag to tell that
304 $me->{_data}->{file_exist} = 0;
305
306 #note that we keep timer on, until the file is back
307 #if we were lucky, we got every entry before it was rotate
308 #otherwise we probably lost the lasts entrys
309 #For all effects, we behave like we never lost it (since
310 # we can't guess :\ )
311
312 #supose you are watching procmail's log file
313 #if the user rotates the from file from the procfile,
314 #he has to make sure that he rotates the file before delivering mail,
315 #as procmail is called when receives a mail
316 #otherwise we will lost that entry for sure. (sad!)
317 #and we will only note that after that mbox is opened.
318  
319 #reset the counter
320 $me->{_data}->{timer_count} = 0;
321  
322 #close the file and cancels the watcher
323 $me->_close_file();
324 }
325 return;
326 }
327
328 #was it trucated/rotated and we already noticed it before?
329 if ($me->{_data}->{file_exist} == 0){
330 #now the file is back, we need to reopen it again
331
332 #we need to get this data back..
333 $me->{_data}->{file_count} = 0;
334 $me->{_data}->{file_footprint} = [];
335
336 #we can stop the timer for now
337 $me->{_watchers}->{timer}->stop;
338
339 #reset the counter
340 $me->{_data}->{timer_count} = 0;
341
342 #open it again
343 $me->_open_file();
344  
345 return;
346 }
347  
348 #checks if we got to the limit
349 if ($me->{_data}->{timer_count} == $me->{_arg}->{timeout}){
350  
351 $me->{_data}->{timer_count} = 0;
352  
353 #The file might have being rotated and we didn't notice it
354 $me->_close_file();
355 $me->_open_file(1);
356  
357 #there is a great chance that the file is the same as before,
358 #so we need to check it again
359 if ($me->_file_check_sanity() == 0){
360  
361 #reset our counters
362 $me->{_data}->{file_count} = 0;
363 $me->{_data}->{file_footprint} = [];
364 }
365 else{
366 #The timout callback
367 &{$me->{_arg}->{timeout_cb}}($me);
368 }
369
370 #we can stop the timer for now
371 $me->{_watchers}->{timer}->stop;
372 $me->{_watchers}->{read}->again;
373  
374 return;
375 }
376  
377  
378 #default behaviour
379
380 $me->{_watchers}->{timer}->stop;
381 $me->{_watchers}->{read}->again;
382 }
383  
384  
385  
386  
387 ######################################
388 # _close_file
389 # Closes the file and cancels the
390 # watcher
391 ###################################
392 sub _close_file{
393 my ($me) = @_;
394  
395 #cancel the watcher and make sure we don't hold any reference to it
396 $me->{_watchers}->{read}->cancel;
397 undef $me->{_watchers}->{read};
398
399 #close the FH
400 $me->{fd}->close();
401 undef $me->{fd};
402 }
403  
404  
405 ###########################################
406 # _open_file:
407 # Open the file and start the watcher to it
408 ###############
409 sub _open_file{
410 my ($me, $parked) =@_;
411  
412 if (!defined($parked)){
413 $parked = 0;
414 }
415  
416 #open it
417 $me->{fd} = new IO::File $me->{_arg}->{file}, "r"
418 or die "Error!! Could not open file: ". $me->{_arg}->{file} ."\nReason: $!\n";
419
420 #it exists
421 $me->{_data}->{file_exist} = 1;
422  
423 #the file read watcher
424 $me->{_watchers}->{read} = Event->io(
425 fd => $me->{fd},
426 cb => [$me, "_file_read"],
427 poll => 'r',
428 desc => 'Helper watcher for Event::File->tail ID:' . $me->{_data}->{id},
429 parked => $parked,
430 );
431 }
432  
433 ##################################################
434 # _file_check_sanity:
435 # Checks if the from file still the same
436 # as before.
437 # If it is in sync, it will update the
438 # position to where we left off.
439 # It returns:
440 # 0 => file out of sync (start from the beggining)
441 # 1 => file in sync
442 ################################
443 sub _file_check_sanity{
444 my ($me) = @_;
445 my ($size, $line, $file_line, $old_position, $handler, $file_ok);
446
447 $size = (stat($me->{_arg}->{file}))[7];
448 $old_position = $me->{_arg}->{position};
449 $handler = $me->{fd};
450  
451 #Check if it is possible to be the same file
452 if ( $size >= $old_position ){
453  
454 #checks each line
455 #note that this will not block because of the size check above
456 #if the file shrinks, we better start all over because it would be impossible
457 #to know what exaclty happened
458 $file_ok = 1;
459 SANITY_CHECK:
460 foreach $line (@{$me->{_data}->{file_footprint}}){
461  
462 #read it
463 $file_line = <$handler>;
464 chomp ($file_line);
465
466 if ($file_line ne $line){
467 #out of sync!
468 $file_ok = 0;
469 last SANITY_CHECK;
470 }
471 }
472 #put the file in the desired position
473 if ($file_ok){
474 $handler->seek($old_position, 0);
475 }else{
476 $handler->seek(0, 0);
477 }
478 }
479
480 #We don't trust a file if it is less than it was before
481 else{
482 $file_ok = 0;
483 }
484  
485 $me->{_data}->{file_ok} = $file_ok;
486  
487 #returns the result
488 return $file_ok;
489 }
490  
491 =head2 $watcher->desc;
492  
493 Returns the description of the watcher.
494  
495 =cut
496  
497 sub desc{
498 my ($me) = @_;
499 return $me->{_arg}->{desc};
500 }
501  
502 =head2 $watcher->id;
503  
504 Returns the internal watcher id number.
505  
506 =cut
507  
508 sub id{
509 my ($me) = @_;
510 return $me->{_data}->{id};
511 }
512  
513 =head2 $position = $watcher->position;
514  
515 Returns the current file position
516  
517 =cut
518  
519 #WARNING: the file position is updated only when it gets to the end of the
520 #file
521 sub position{
522 my ($me) = @_;
523 return $me->{_arg}->{position};
524 }
525  
526 =head2 $array_ref = $watcher->footprint;
527  
528 This will return an array reference of the file's footprint.
529 This is handy if you need to quit your application and after restarting it the
530 file can be checked whether it is the same or not.
531  
532 =cut
533  
534 sub footprint{
535 my ($me) = @_;
536 return $me->{_data}->{file_footprint};
537 }
538  
539 =head2 $result = $watcher->loop($timeout);
540  
541 loop is a wrapper to C<Event::loop> in case that no other Event's watcher is in use.
542 You have to call it somewhere to let Event watch the
543 file for you.
544 C<$result> will return from the C<$result> value passed by an C<unloop> method (see below).
545 Please refer to the loop function in the Event pod page for more info.
546  
547 =cut
548  
549 #'loop wrapper
550 sub loop{
551 my ($me, $timeout) = @_;
552 return Event::loop($timeout);
553 }
554  
555 =head2 $watcher->unloop($result);
556  
557 A wrapper to C<Event::unloop>. This will cancel an active Event::loop, e.g.
558 when called from a callback.
559 C<$result> will be passed to the C<loop> caller.
560 Please refer to Event::unloop for more info.
561  
562 =cut
563  
564 #unloop wrapper
565 sub unloop{
566 my ($me, $result) = @_;
567 Event::unloop($result);
568 }
569  
570 =head2 $watcher->sweep;
571  
572 A wrapper around C<Event::sweep>.
573 C<sweep> will call any event pending and return.
574 Please refer to C<Event::sweep> for mor info.
575  
576 =cut
577  
578 #Sweep wrapper
579 sub sweep{
580 my ($me, $prio) = @_;
581 Event::sweep($prio);
582 }
583  
584 =head2 $watcher->stop;
585  
586 This will stop the watcher until a C<again> or C<start> method is called.
587  
588 =cut
589  
590 sub stop{
591 my ($me) = @_;
592 $me->{_watchers}->{read}->stop;
593 $me->{_watchers}->{timer}->stop;
594 }
595  
596 =head2 $watcher->start;
597  
598 This method will restart the watcher
599  
600 =cut
601  
602 sub start{
603 my ($me) = @_;
604 $me->{_watchers}->{read}->stop;
605 $me->{_watchers}->{timer}->start;
606 }
607  
608 =head2 $watcher->again;
609  
610 The same as C<start>
611  
612 =cut
613  
614 sub again{
615 my ($me) = @_;
616 $me->start;
617 }
618  
619 =head2 $watcher->cancel
620  
621 This will destroy the watcher.
622 Note that if t there is a reference to this watcher outside this package,
623 the memory won't be freed.
624  
625 =cut
626  
627 #'
628 sub cancel{
629 my ($me) = @_;
630 $me->{_watchers}->{read}->cancel;
631 $me->{_watchers}->{timer}->cancel;
632 undef $me;
633 }
634  
635  
636 1;
637  
638 __END__