diff --git a/lib/Pingback.pm b/lib/Pingback.pm index d154a85c..2159b7b5 100644 --- a/lib/Pingback.pm +++ b/lib/Pingback.pm @@ -28,8 +28,11 @@ use English qw(-no_match_vars); use constant PTDEBUG => $ENV{PTDEBUG} || 0; -use File::Basename (); -use Data::Dumper (); +use File::Basename qw(); +use Data::Dumper qw(); +use Fcntl qw(:DEFAULT); + +use File::Spec; sub Dumper { local $Data::Dumper::Indent = 1; @@ -124,6 +127,42 @@ sub pingback { return \@suggestions; } +my $one_day = 60 * 60 * 24; +sub time_to_check { + my ($file) = @_; + + if ( !$file ) { + my $dir = File::Spec->tmpdir(); + $file = File::Spec->catfile($dir, 'percona-toolkit-version-check'); + } + my $mtime = (stat $file)[9]; + + # If there isn't an mtime, the file (probably) doesn't exist, so + # touch it and return true. + if ( !defined $mtime ) { + _touch($file); + return 1; + } + + # Otherwise, if there's been more than a day since the last check, + # update the file and return true. + my $time = int(time()); + if ( ($time - $mtime) > $one_day ) { + _touch($file); + return 1; + } + + # Otherwise, we're still within the day, so don't do the version check. + return; +} + +sub _touch { + my ($file) = @_; + sysopen my $fh, $file, O_WRONLY|O_CREAT|O_NONBLOCK + or die "Cannot create $file : $!"; + close $fh or die "Cannot close $file : $!"; +} + sub encode_client_response { my (%args) = @_; my @required_args = qw(items versions); diff --git a/t/lib/Pingback.t b/t/lib/Pingback.t index 9b7747b8..60fc3bb8 100644 --- a/t/lib/Pingback.t +++ b/t/lib/Pingback.t @@ -179,6 +179,42 @@ SKIP: { ); } +# ############################################################################# +# Testing time_to_check +# ############################################################################# + +my $dir = File::Spec->tmpdir(); +my $file = File::Spec->catfile($dir, 'percona-toolkit-version-check-test'); + +unlink $file; + +ok( + Pingback::time_to_check($file), + "time_to_check() returns true if the file doesn't exist", +); + +ok( + !Pingback::time_to_check($file), + "...but false if it exists and it's been less than 24 hours", +); + +my $one_day = 60 * 60 * 24; +my ($old_atime, $old_mtime) = (stat($file))[8,9]; + +utime($old_atime - $one_day * 2, $old_mtime - $one_day * 2, $file); + +cmp_ok( + (stat($file))[9], + q{<}, + time() - $one_day, + "Sanity check, the file's mtime is now at least one day behind time()", +); + +ok( + Pingback::time_to_check($file), + "time_to_check returns true if the file exists and it's mtime is at least one day old", +); + # ############################################################################# # Done. # #############################################################################