Advertisement
Guest User

Untitled

a guest
May 3rd, 2012
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 25.56 KB | None | 0 0
  1. package File::Tail;
  2.  
  3. use strict;
  4. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
  5.  
  6. require Exporter;
  7.  
  8. @ISA = qw(Exporter);
  9. # Items to export into callers namespace by default. Note: do not export
  10. # names by default without a very good reason. Use EXPORT_OK instead.
  11. # Do not simply export all your public functions/methods/constants.
  12. $VERSION = '0.99.3';
  13.  
  14.  
  15. # Preloaded methods go here.
  16.  
  17. use FileHandle;
  18. #use IO::Seekable; # does not define SEEK_SET in 5005.02
  19. use File::stat;
  20. use Carp;
  21. use Time::HiRes qw ( time sleep ); #import hires microsecond timers
  22.  
  23. sub SEEK_SET   () {0;}
  24. sub SEEK_CUR () {1;}
  25. sub SEEK_END   () {2;}
  26.  
  27.  
  28. sub interval {
  29.     my $object=shift @_;
  30.     if (@_) {
  31.     $object->{interval}=shift;
  32.     $object->{interval}=$object->{maxinterval} if
  33.         $object->{interval}>$object->{maxinterval};
  34.     }
  35.     $object->{interval};
  36. }
  37.  
  38. sub logit {
  39.     my $object=shift;
  40.     my @call=caller(1);
  41.     print # STDERR
  42. #   time()." ".
  43.     "\033[7m".
  44.         $call[3]." ".$object->{"input"}." ".join("",@_).
  45.         "\033[0m".
  46.             "\n"
  47.     if $object->debug;
  48. }
  49.  
  50. sub adjustafter {
  51.     my $self=shift;
  52.     $self->{adjustafter}=shift if @_;
  53.     return $self->{adjustafter};
  54. }
  55.  
  56. sub debug {
  57.     my $self=shift;
  58.     $self->{"debug"}=shift if @_;
  59.     return $self->{"debug"};
  60. }
  61.  
  62. sub errmode {
  63.     my($self, $mode) = @_;
  64.     my($prev) = $self->{errormode};
  65.  
  66.     if (@_ >= 2) {
  67.         ## Set the error mode.
  68.     defined $mode or $mode = '';
  69.     if (ref($mode) eq 'CODE') {
  70.         $self->{errormode} = $mode;
  71.     } elsif (ref($mode) eq 'ARRAY') {
  72.         unless (ref($mode->[0]) eq 'CODE') {
  73.         croak 'bad errmode: first item in list must be a code ref';
  74.         $mode = 'die';
  75.         }
  76.         $self->{errormode} = $mode;
  77.     } else {
  78.         $self->{errormode} = lc $mode;
  79.     }
  80.     }
  81.      $prev;
  82. }
  83.  
  84. sub errmsg {
  85.     my($self, @errmsgs) = @_;
  86.     my($prev) = $self->{errormsg};
  87.  
  88.     if (@_ > 0) {
  89.         $self->{errormsg} = join '', @errmsgs;
  90.     }
  91.  
  92.     $prev;
  93. } # end sub errmsg
  94.  
  95.  
  96. sub error {
  97.     my($self, @errmsg) = @_;
  98.     my(
  99.        $errmsg,
  100.        $func,
  101.        $mode,
  102.        @args,
  103.        );
  104.  
  105.     if (@_ >= 1) {
  106.         ## Put error message in the object.
  107.         $errmsg = join '', @errmsg;
  108.         $self->{"errormsg"} = $errmsg;
  109.  
  110.         ## Do the error action as described by error mode.
  111.         $mode = $self->{"errormode"};
  112.         if (ref($mode) eq 'CODE') {
  113.             &$mode($errmsg);
  114.             return;
  115.         } elsif (ref($mode) eq 'ARRAY') {
  116.             ($func, @args) = @$mode;
  117.             &$func(@args);
  118.             return;
  119.         } elsif ($mode eq "return") {
  120.             return;
  121.     } elsif ($mode eq "warn") {
  122.         carp $errmsg;
  123.         } else {  # die
  124.         croak $errmsg;
  125.     }
  126.     } else {
  127.         return $self->{"errormsg"} ne '';
  128.     }
  129. } # end sub error
  130.  
  131.  
  132. sub copy {
  133.     my $self=shift;
  134.     $self->{copy}=shift if @_;
  135.     return $self->{copy};
  136. }
  137.  
  138. sub tail {
  139.     my $self=shift;
  140.     $self->{"tail"}=shift if @_;
  141.     return $self->{"tail"};
  142. }
  143.  
  144. sub reset_tail {
  145.     my $self=shift;
  146.     $self->{reset_tail}=shift if @_;
  147.     return $self->{reset_tail};
  148. }
  149.  
  150. sub nowait {
  151.     my $self=shift;
  152.     $self->{nowait}=shift if @_;
  153.     return $self->{nowait};
  154. }
  155.  
  156. sub method {
  157.     my $self=shift;
  158.     $self->{method}=shift if @_;
  159.     return $self->{method};
  160. }
  161.  
  162. sub input {
  163.     my $self=shift;
  164.     $self->{input}=shift if @_;
  165.     return $self->{input};
  166. }
  167.  
  168. sub maxinterval {
  169.     my $self=shift;
  170.     $self->{maxinterval}=shift if @_;
  171.     return $self->{maxinterval};
  172. }
  173.  
  174. sub resetafter {
  175.     my $self=shift;
  176.     $self->{resetafter}=shift if @_;
  177.     return $self->{resetafter};
  178. }
  179.  
  180. sub ignore_nonexistant {
  181.     my $self=shift;
  182.     $self->{ignore_nonexistant}=shift if @_;
  183.     return $self->{ignore_nonexistant};
  184. }
  185.  
  186. sub name_changes {
  187.     my $self=shift;
  188.     $self->{name_changes_callback}=shift if @_;
  189.     return $self->{name_changes_callback};
  190. }
  191.  
  192. sub TIEHANDLE {
  193.     my $ref=new(@_);
  194. }
  195.  
  196. sub READLINE {
  197.     $_[0]->read();
  198. }
  199.  
  200. sub PRINT {
  201.   $_[0]->error("PRINT makes no sense in File::Tail");
  202. }
  203.  
  204. sub PRINTF {
  205.   $_[0]->error("PRINTF makes no sense in File::Tail");
  206. }
  207.  
  208. sub READ {
  209.   $_[0]->error("READ not implemented in File::Tail -- use READLINE (<HANDLE>) instead");
  210. }
  211.  
  212. sub GETC {
  213.   $_[0]->error("GETC not (yet) implemented in File::Tail -- use READLINE (<HANDLE>) instead");
  214. }
  215.  
  216. sub DESTROY {
  217.   my($this) = $_[0];
  218.   close($this->{"handle"}) if (defined($this) && defined($this->{'handle'}));
  219. #  undef $_[0];
  220.   return;
  221. }
  222.  
  223. sub CLOSE {
  224.     &DESTROY(@_);
  225. }
  226.  
  227. sub new {
  228.     my ($pkg)=shift @_;
  229.     $pkg=ref($pkg) || $pkg;
  230.     unless ($pkg) {
  231.     $pkg="File::Tail";
  232.     }
  233.     my %params;
  234.     if ($#_ == 0)  {
  235.     $params{"name"}=$_[0];
  236.     } else {
  237.     if (($#_ % 2) != 1) {
  238.         croak "Odd number of parameters for new";
  239.         return;
  240.     }
  241.     %params=@_;
  242.     }
  243.     my $object = {};
  244.     bless $object,$pkg;
  245.     unless (defined($params{'name'})) {
  246.     croak "No file name given. Pass filename as \"name\" parameter";
  247.     return;
  248.     }
  249.     $object->input($params{'name'});
  250.     $object->copy($params{'cname'});
  251.     $object->method($params{'method'} || "tail");
  252.     $object->{buffer}="";
  253.     $object->maxinterval($params{'maxinterval'} || 60);
  254.     $object->interval($params{'interval'} || 10);
  255.     $object->adjustafter($params{'adjustafter'} || 10);
  256.     $object->errmode($params{'errmode'} || "die");
  257.     $object->resetafter($params{'resetafter'} ||
  258.              ($object->maxinterval*$object->adjustafter));
  259.     $object->{"debug"}=($params{'debug'} || 0);
  260.     $object->{"tail"}=($params{'tail'} || 0);
  261.     $object->{"nowait"}=($params{'nowait'} || 0);
  262.     $object->{"maxbuf"}=($params{'maxbuf'} || 16384);
  263.     $object->{"name_changes_callback"}=($params{'name_changes'} || undef);
  264.     if (defined $params{'reset_tail'}) {
  265.         $object->{"reset_tail"} = $params{'reset_tail'};
  266.     } else {
  267.         $object->{"reset_tail"} =  -1;
  268.     }
  269.     $object->{'ignore_nonexistant'}=($params{'ignore_nonexistant'} || 0);
  270.     $object->{"lastread"}=0;
  271.     $object->{"sleepcount"}=0;
  272.     $object->{"lastcheck"}=0;
  273.     $object->{"lastreset"}=0;
  274.     $object->{"nextcheck"}=time();
  275.     if ($object->{"method"} eq "tail") {
  276.     $object->reset_pointers;
  277.     }
  278. #    $object->{curpos}=0;        # ADDED 25May01: undef warnings when
  279. #    $object->{endpos}=0;        #   starting up on a nonexistant file
  280.     return $object;
  281. }
  282.  
  283. # Sets position in file when first opened or after that when reset:
  284. # Sets {endpos} and {curpos} for current {handle} based on {tail}.
  285. # Sets {tail} to value of {reset_tail}; effect is that first call
  286. # uses {tail} and subsequent calls use {reset_tail}.
  287. sub position {
  288.     my $object=shift;
  289.     $object->{"endpos"}=sysseek($object->{handle},0,SEEK_END);
  290.     unless ($object->{"tail"}) {
  291.     $object->{endpos}=$object->{curpos}=
  292.         sysseek($object->{handle},0,SEEK_END);
  293.     } elsif ($object->{"tail"}<0) {
  294.     $object->{endpos}=sysseek($object->{handle},0,SEEK_END);
  295.     $object->{curpos}=sysseek($object->{handle},0,SEEK_SET);
  296.     } else {
  297.     my $crs=0;
  298.     my $maxlen=sysseek($object->{handle},0,SEEK_END);
  299.     while ($crs<$object->{"tail"}+1) {
  300.         my $avlen=length($object->{"buffer"})/($crs+1);
  301.         $avlen=80 unless $avlen;
  302.         my $calclen=$avlen*$object->{"tail"};
  303.         $calclen+=1024 if $calclen<=length($object->{"buffer"});
  304.         $calclen=$maxlen if $calclen>$maxlen;
  305.         $object->{curpos}=sysseek($object->{handle},-$calclen,SEEK_END);
  306.         sysread($object->{handle},$object->{"buffer"},
  307.             $calclen);
  308.         $object->{curpos}=sysseek($object->{handle},0,SEEK_CUR);
  309.         $crs=$object->{"buffer"}=~tr/\n//;
  310.         last if ($calclen>=$maxlen);
  311.     }
  312.     $object->{curpos}=sysseek($object->{handle},0,SEEK_CUR);
  313.     $object->{endpos}=sysseek($object->{handle},0,SEEK_END);
  314.     if ($crs>$object->{"tail"}) {
  315.         my $toskip=$crs-$object->{"tail"};
  316.         my $pos;
  317.         $pos=index($object->{"buffer"},"\n");
  318.         while (--$toskip) {
  319.         $pos=index($object->{"buffer"},"\n",$pos+1);
  320.         }
  321.         $object->{"buffer"}=substr($object->{"buffer"},$pos+1);
  322.     }
  323.     }
  324.     $object->{"tail"}=$object->{"reset_tail"};
  325. }
  326.  
  327. # Tries to open or reopen the file; failure is an error unless
  328. # {ignore_nonexistant} is set.
  329. #
  330. # For a new file (ie, first time opened) just does some book-keeping
  331. # and calls position for initial position setup.  Otherwise does some
  332. # checks whether file has been replaced, and if so changes to the new
  333. # file.  (Calls position for reset setup).
  334. #
  335. # Always updates {lastreset} to current time.
  336. #
  337. sub reset_pointers {
  338.     my $object=shift @_;
  339.     $object->{lastreset} = time();
  340.  
  341.     my $st;
  342.  
  343.     my $oldhandle=$object->{handle};
  344.     my $newhandle=FileHandle->new;
  345.  
  346.     my $newname;
  347.     if ($oldhandle && $$object{'name_changes_callback'}) {
  348.     $newname=$$object{'name_changes_callback'}();
  349.     } else {
  350.     $newname=$object->input;
  351.     }
  352.  
  353.     unless (open($newhandle,"<$newname")) {
  354.     if ($object->{'ignore_nonexistant'}) {
  355.          # If we have an oldhandle, leave endpos and curpos to what they
  356.          # were, since oldhandle will still be the "current" handle elsewhere,
  357.          # eg, checkpending.  This also allows tailing a file which is removed
  358.          # but still being written to.
  359.             if (!$oldhandle) {
  360.                 $object->{'endpos'}=0;
  361.                 $object->{'curpos'}=0;
  362.             }
  363.         return;
  364.     }
  365.     $object->error("Error opening ".$object->input.": $!");
  366.     $object->{'endpos'}=0 unless defined($object->{'endpos'});
  367.     $object->{'curpos'}=0 unless defined($object->{'curpos'});
  368.     return;
  369.     }
  370.     binmode($newhandle);
  371.    
  372.     if (defined($oldhandle)) {
  373.     # If file has not been changed since last OK read do not do anything
  374.     $st=stat($newhandle);
  375.     # lastread uses fractional time, stat doesn't. This can cause false
  376.         # negatives.
  377.         # If the file was changed the same second as it was last read,
  378.         # we only reopen it if it's length has changed. The alternative is that
  379.         # sometimes, files would be reopened needlessly, and with reset_tail
  380.     # set to -1, we would see the whole file again.
  381.     # Of course, if the file was removed the same second as when it was
  382.         # last read, and replaced (within that second) with a file of equal
  383.         # length, we're out of luck. I don't see how to fix this.
  384.     if ($st->mtime<=int($object->{'lastread'})) {
  385.         if ($st->size==$object->{"curpos"}) {
  386.         $object->{lastread} = $st->mtime;
  387.         return;
  388.         } else {
  389.         # will continue further to reset
  390.         }
  391.     } else {
  392.     }
  393.     $object->{handle}=$newhandle;
  394.     $object->position;
  395.     $object->{lastread} = $st->mtime;
  396.     close($oldhandle);
  397.     } else {                  # This is the first time we are opening this file
  398.     $st=stat($newhandle);
  399.     $object->{handle}=$newhandle;
  400.     $object->position;
  401.     $object->{lastread}=$st->mtime; # for better estimate on initial read
  402.     }
  403.    
  404. }
  405.  
  406.  
  407. sub checkpending {
  408.    my $object=shift @_;
  409.  
  410.    my $old_lastcheck = $object->{lastcheck};
  411.    $object->{"lastcheck"}=time;
  412.    unless ($object->{handle}) {
  413.        $object->reset_pointers;
  414.        unless ($object->{handle}) { # This try did not open the file either
  415.        return 0;
  416.        }
  417.    }
  418.    
  419.    $object->{"endpos"}=sysseek($object->{handle},0,SEEK_END);
  420.    if ($object->{"endpos"}<$object->{curpos}) {  # file was truncated
  421.        $object->position;
  422.    } elsif (($object->{curpos}==$object->{"endpos"})
  423.            && (time()-$object->{lastread})>$object->{'resetafter'}) {
  424.        $object->reset_pointers;
  425.        $object->{"endpos"}=sysseek($object->{handle},0,SEEK_END);
  426.    }
  427.  
  428.    if ($object->{"endpos"}-$object->{curpos}) {
  429.        sysseek($object->{handle},$object->{curpos},SEEK_SET);
  430.        readin($object,$object->{"endpos"}-$object->{curpos});
  431.    }
  432.    return ($object->{"endpos"}-$object->{curpos});
  433. }
  434.  
  435. sub predict {
  436.     my $object=shift;
  437.     my $crs=$object->{"buffer"}=~tr/\n//; # Count newlines in buffer
  438.     my @call=caller(1);
  439.     return 0 if $crs;
  440.     my $ttw=$object->{"nextcheck"}-time();
  441.     return $ttw if $ttw>0;
  442.     if (my $len=$object->checkpending) {
  443.     readin($object,$len);
  444.     return 0;
  445.     }
  446.     if ($object->{"sleepcount"}>$object->adjustafter) {
  447.     $object->{"sleepcount"}=0;
  448.     $object->interval($object->interval*10);
  449.     }
  450.     $object->{"sleepcount"}++;
  451.     $object->{"nextcheck"}=time()+$object->interval;
  452.     return ($object->interval);
  453. }
  454.  
  455. sub bitprint {
  456.     return "undef" unless defined($_[0]);
  457.     return unpack("b*",$_[0]);
  458. }
  459.  
  460. sub select {
  461.     my $object=shift @_  if ref($_[0]);
  462.     my ($timeout,@fds)=splice(@_,3);
  463.     $object=$fds[0] unless defined($object);
  464.     my ($savein,$saveout,$saveerr)=@_;
  465.     my ($minpred,$mustreturn);
  466.     if (defined($timeout)) {
  467.     $minpred=$timeout;
  468.     $mustreturn=time()+$timeout;
  469.     } else {
  470.     $minpred=$fds[0]->predict;
  471.     }
  472.     foreach (@fds) {
  473.     my $val=$_->predict;
  474.     $minpred=$val if $minpred>$val;
  475.     }
  476.     my ($nfound,$timeleft);
  477.     my @retarr;
  478.     while (defined($timeout)?(!$nfound && (time()<$mustreturn)):!$nfound) {
  479. # Restore bitmaps in case we called select before
  480.     splice(@_,0,3,$savein,$saveout,$saveerr);
  481.  
  482.  
  483.     ($nfound,$timeleft)=select($_[0],$_[1],$_[2],$minpred);
  484.  
  485.  
  486.     if (defined($timeout)) {
  487.         $minpred=$timeout;
  488.     } else {
  489.         $minpred=$fds[0]->predict;
  490.     }
  491.     undef @retarr;
  492.     foreach (@fds) {
  493.         my $val=$_->predict;
  494.         $nfound++ unless $val;
  495.         $minpred=$val if $minpred>$val;
  496.         push(@retarr,$_) unless $val;
  497.     }
  498.     }
  499.     if (wantarray) {
  500.     return ($nfound,$timeleft,@retarr);
  501.     } else {
  502.     return $nfound;
  503.     }
  504. }
  505.  
  506. sub readin {
  507.     my $crs;
  508.     my ($object,$len)=@_;
  509.     if (length($object->{"buffer"})) {
  510.     # this means the file was reset AND a tail -n was active
  511.     $crs=$object->{"buffer"}=~tr/\n//; # Count newlines in buffer
  512.     return $crs if $crs;
  513.     }
  514.     $len=$object->{"maxbuf"} if ($len>$object->{"maxbuf"});
  515.     my $nlen=$len;
  516.     while ($nlen>0) {
  517.     $len=sysread($object->{handle},$object->{"buffer"},
  518.              $nlen,length($object->{"buffer"}));
  519.     return 0 if $len==0; # Some busy filesystems return 0 sometimes,
  520.                              # and never give anything more from then on if
  521.                              # you don't give them time to rest. This return
  522.                              # allows File::Tail to use the usual exponential
  523.                              # backoff.
  524.     $nlen=$nlen-$len;
  525.     }
  526.     $object->{curpos}=sysseek($object->{handle},0,SEEK_CUR);
  527.    
  528.     $crs=$object->{"buffer"}=~tr/\n//;
  529.    
  530.     if ($crs) {
  531.     my $tmp=time;
  532.     $object->{lastread}=$tmp if $object->{lastread}>$tmp; #???
  533.     $object->interval(($tmp-($object->{lastread}))/$crs);
  534.     $object->{lastread}=$tmp;
  535.     }
  536.     return ($crs);
  537. }
  538.  
  539. sub read {
  540.     my $object=shift @_;
  541.     my $len;
  542.     my $pending=$object->{"endpos"}-$object->{"curpos"};
  543.     my $crs=$object->{"buffer"}=~m/\n/;
  544.     while (!$pending && !$crs) {
  545.     $object->{"sleepcount"}=0;
  546.     while ($object->predict) {
  547.         if ($object->nowait) {
  548.         if (wantarray) {
  549.             return ();
  550.         } else {
  551.             return "";
  552.         }
  553.         }
  554.         sleep($object->interval) if ($object->interval>0);
  555.     }
  556.     $pending=$object->{"endpos"}-$object->{"curpos"};
  557.     $crs=$object->{"buffer"}=~m/\n/;
  558.     }
  559.    
  560.     if (!length($object->{"buffer"}) || index($object->{"buffer"},"\n")<0) {
  561.     readin($object,$pending);
  562.     }
  563.     unless (wantarray) {
  564.     my $str=substr($object->{"buffer"},0,
  565.                1+index($object->{"buffer"},"\n"));
  566.     $object->{"buffer"}=substr($object->{"buffer"},
  567.                    1+index($object->{"buffer"},"\n"));
  568.     return $str;
  569.     } else {
  570.     my @str;
  571.     while (index($object->{"buffer"},"\n")>-1) {
  572.         push(@str,substr($object->{"buffer"},0,
  573.                  1+index($object->{"buffer"},"\n")));
  574.         $object->{"buffer"}=substr($object->{"buffer"},
  575.                        1+index($object->{"buffer"},"\n"));
  576.  
  577.     }
  578.     return @str;
  579.     }
  580. }
  581.  
  582. 1;
  583.  
  584. __END__
  585.  
  586. =head1 NAME
  587.  
  588. File::Tail - Perl extension for reading from continously updated files
  589.  
  590. =head1 SYNOPSIS
  591.  
  592.   use File::Tail;
  593.   $file=File::Tail->new("/some/log/file");
  594.   while (defined($line=$file->read)) {
  595.       print "$line";
  596.   }
  597.  
  598.   use File::Tail;
  599.   $file=File::Tail->new(name=>$name, maxinterval=>300, adjustafter=>7);
  600.   while (defined($line=$file->read)) {
  601.       print "$line";
  602.   }
  603.  
  604. OR, you could use tie (additional parameters can be passed with the name, or
  605. can be set using $ref):
  606.  
  607.     use File::Tail;
  608.     my $ref=tie *FH,"File::Tail",(name=>$name);
  609.     while (<FH>) {
  610.         print "$_";
  611.     }
  612.  
  613.  
  614. Note that the above script will never exit. If there is nothing being written
  615. to the file, it will simply block.
  616.  
  617. You can find more synopsii in the file logwatch, which is included
  618. in the distribution.
  619.  
  620. Note: Select functionality was added in version 0.9, and it required
  621. some reworking of all routines. ***PLEASE*** let me know if you see anything
  622. strange happening.
  623.  
  624. You can find two way of using select in the file select_demo which is included
  625. in the ditribution.
  626.  
  627. =head1 DESCRIPTION
  628.  
  629. The primary purpose of File::Tail is reading and analysing log files while
  630. they are being written, which is especialy usefull if you are monitoring
  631. the logging process with a tool like Tobias Oetiker's MRTG.
  632.  
  633. The module tries very hard NOT to "busy-wait" on a file that has little
  634. traffic. Any time it reads new data from the file, it counts the number
  635. of new lines, and divides that number by the time that passed since data
  636. were last written to the file before that. That is considered the average
  637. time before new data will be written. When there is no new data to read,
  638. C<File::Tail> sleeps for that number of seconds. Thereafter, the waiting
  639. time is recomputed dynamicaly. Note that C<File::Tail> never sleeps for
  640. more than the number of seconds set by C<maxinterval>.
  641.  
  642. If the file does not get altered for a while, C<File::Tail> gets suspicious
  643. and startschecking if the file was truncated, or moved and recreated. If
  644. anything like that had happened, C<File::Tail> will quietly reopen the file,
  645. and continue reading. The only way to affect what happens on reopen is by
  646. setting the reset_tail parameter (see below). The effect of this is that
  647. the scripts need not be aware when the logfiles were rotated, they will
  648. just quietly work on.
  649.  
  650. Note that the sleep and time used are from Time::HiRes, so this module
  651. should do the right thing even if the time to sleep is less than one second.
  652.  
  653. The logwatch script (also included) demonstrates several ways of calling
  654. the methods.
  655.  
  656. =head1 CONSTRUCTOR
  657.  
  658. =head2 new ([ ARGS ])
  659.  
  660. Creates a C<File::Tail>. If it has only one paramter, it is assumed to
  661. be the filename. If the open fails, the module performs a croak. I
  662. am currently looking for a way to set $! and return undef.
  663.  
  664. You can pass several parameters to new:
  665.  
  666. =over 4
  667.  
  668. =item name
  669.  
  670. This is the name of the file to open. The file will be opened for reading.
  671. This must be a regular file, not a pipe or a terminal (i.e. it must be
  672. seekable).
  673.  
  674. =item maxinterval
  675.  
  676. The maximum number of seconds (real number) that will be spent sleeping.
  677. Default is 60, meaning C<File::Tail> will never spend more than sixty
  678. seconds without checking the file.
  679.  
  680. =item interval
  681.  
  682. The initial number of seconds (real number) that will be spent sleeping,
  683. before the file is first checked. Default is ten seconds, meaning C<File::Tail>
  684. will sleep for 10 seconds and then determine, how many new lines have appeared
  685. in the file.
  686.  
  687. =item adjustafter
  688.  
  689. The number of C<times> C<File::Tail> waits for the current interval,
  690. before adjusting the interval upwards. The default is 10.
  691.  
  692. =item resetafter
  693.  
  694. The number of seconds after last change when C<File::Tail> decides
  695. the file may have been closed and reopened. The default is
  696. adjustafter*maxinterval.
  697.  
  698. =item maxbuf
  699.  
  700. The maximum size of the internal buffer. When File::Tail
  701. suddenly found an enormous ammount of information in the file
  702. (for instance if the retry parameters were set to very
  703. infrequent checking and the file was rotated), File::Tail
  704. sometimes slurped way too much file into memory.  This sets
  705. the maximum size of File::Tail's buffer.
  706.  
  707. Default value is 16384 (bytes).
  708.  
  709. A large internal buffer may result in worse performance (as well as
  710. increased memory usage), since File::Tail will have to do more work
  711. processing the internal buffer.
  712.  
  713. =item nowait
  714.  
  715. Does not block on read, but returns an empty string if there is nothing
  716. to read. DO NOT USE THIS unless you know what you are doing. If you
  717. are using it in a loop, you probably DON'T know what you are doing.
  718. If you want to read tails from multiple files, use select.
  719.  
  720.  
  721. =item ignore_nonexistant
  722.  
  723.     Do not complain if the file doesn't exist when it is first
  724. opened or when it is to be reopened. (File may be reopened after
  725. resetafter seconds have passed since last data was found.)
  726.  
  727. =item tail
  728.  
  729.     When first started, read and return C<n> lines from the file.
  730. If C<n> is zero, start at the end of file. If C<n> is negative,
  731. return the whole file.
  732.  
  733.     Default is C<0>.
  734.  
  735. =item reset_tail
  736.  
  737.     Same as tail, but applies after reset. (i.e. after the
  738. file has been automaticaly closed and reopened). Defaults to
  739. C<-1>, i.e. does not skip any information present in the
  740. file when it first checks it.
  741.  
  742.    Why would you want it otherwise? I've seen files which
  743. have been cycled like this:
  744.  
  745.    grep -v lastmonth log >newlog
  746.    mv log archive/lastmonth
  747.    mv newlog log
  748.    kill -HUP logger
  749.  
  750.  
  751. Obviously, if this happens and you have reset_tail set to
  752. c<-1>, you will suddenly get a whole bunch of lines - lines
  753. you already saw. So in this case, reset_tail should probably
  754. be set to a small positive number or even C<0>.
  755.  
  756. =item name_changes
  757.  
  758. Some logging systems change the name of the file
  759. they are writing to, sometimes to include a date, sometimes a
  760. sequence number, sometimes other, even more bizarre changes.
  761.  
  762. Instead of trying to implement various clever detection methods,
  763. File::Tail will call the code reference defined in name_changes. The code reference should return the string which is the new name of the file to try opening.
  764.  
  765. Note that if the file does not exist, File::Tail will report a fatal error (unless ignore_nonexistant has also been specified).
  766.  
  767. =item debug
  768.  
  769. Set to nonzero if you want to see more about the inner workings of
  770. File::Tail. Otherwise not useful.
  771.  
  772. =item errmode
  773.  
  774. Modeled after the methods from Net:Telnet, here you decide how the
  775. errors should be handled. The parameter can be a code reference which
  776. is called with the error string as a parameter, an array with a code
  777. reference as the first parameter and other parameters to be passed to
  778. handler subroutine, or one of the words:
  779.  
  780. return  - ignore any error (just put error message in errmsg).
  781. warn    - output the error message but continue
  782. die     - display error message and exit
  783.  
  784. Default is die.
  785.  
  786. =back
  787.  
  788. =head1 METHODS
  789.  
  790. =head2 read
  791.  
  792. C<read> returns one line from the input file. If there are no lines
  793. ready, it blocks until there are.
  794.  
  795. =head2 select
  796.  
  797. C<select> is intended to enable the programmer to simoultaneously wait for
  798. input on normal filehandles and File::Tail filehandles. Of course, you may
  799. use it to simply read from more than one File::Tail filehandle at a time.
  800.  
  801.  
  802. Basicaly, you call File::Tail::select just as you would normal select,
  803. with fields for rbits, wbits and ebits, as well as a timeout, however, you
  804. can tack any number of File::Tail objects (not File::Tail filehandles!)
  805. to the end.
  806.  
  807. Usage example:
  808.  
  809.  foreach (@ARGV) {
  810.      push(@files,File::Tail->new(name=>"$_",debug=>$debug));
  811.  }
  812.  while (1) {
  813.    ($nfound,$timeleft,@pending)=
  814.              File::Tail::select(undef,undef,undef,$timeout,@files);
  815.    unless ($nfound) {
  816.      # timeout - do something else here, if you need to
  817.    } else {
  818.      foreach (@pending) {
  819.         print $_->{"input"}." (".localtime(time).") ".$_->read;
  820.    }
  821.  }
  822.  
  823.  #
  824.  # There is a more elaborate example in select_demo in the distribution.
  825.  #
  826.  
  827. When you do this, File::Tail's select emulates normal select, with two
  828. exceptions:
  829.  
  830. a) it will return if there is input on any of the parameters
  831. (i.e. normal filehandles) _or_ File::Tails.
  832.  
  833. b) In addition to C<($nfound, $timeleft)>, the return array will also contain
  834. a list of File::Tail objects which are ready for reading. C<$nfound> will
  835. contain the correct number of filehandles to be read (i.e. both normal
  836. and File::Tails).
  837.  
  838. Once select returns, when you want to determine which File::Tail objects
  839. have input ready, you can either use the list of objects select returned,
  840. or you can check each individual object with $object->predict. This returns
  841. the ammount of time (in fractional seconds) after which the handle expects
  842. input. If it returns 0, there is input waiting. There is no guarantee that
  843. there will be input waiting after the returned number of seconds has passed.
  844. However, File::Tail won't do any I/O on the file until that time has passed.
  845. Note that the value of $timeleft may or may not be correct - that depends on
  846. the underlying operating system (and it's select), so you're better off NOT
  847. relying on it.
  848.  
  849. Also note, if you are determining which files are ready for input by calling
  850. each individual predict, the C<$nfound> value may be invalid, because one
  851. or more of File::Tail object may have become ready between the time select
  852. has returned and the time when you checked it.
  853.  
  854. =head1 TO BE DONE
  855.  
  856. Planned for 1.0: Using $/ instead of \n to
  857. separate "lines" (which should make it possible to read wtmp type files).
  858. Except that I discovered I have no need for that enhancement If you do,
  859. feel free to send me the patches and I'll apply them - if I feel they don't
  860. add too much processing time.
  861.  
  862. =head1 AUTHOR
  863.  
  864. Matija Grabnar, matija.grabnar@arnes.si
  865.  
  866. =head1 SEE ALSO
  867.  
  868. perl(1), tail (1),
  869. MRTG (http://ee-staff.ethz.ch/~oetiker/webtools/mrtg/mrtg.html)
  870.  
  871. =cut
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement