tolerate bigger file sizes in database than on filesystem, consider zero-sized
[BackupPC.git] / bin / BackupPC_incPartsUpdate
index c653db6..1ea28c0 100755 (executable)
@@ -6,12 +6,22 @@ use lib "__INSTALLDIR__/lib";
 use DBI;
 use BackupPC::Lib;
 use BackupPC::View;
+use BackupPC::Attrib qw/:all/;
 use Data::Dumper;
 use Time::HiRes qw/time/;
-use File::Pid;
 use POSIX qw/strftime/;
-use BackupPC::SearchLib;
 use Cwd qw/abs_path/;
+use File::Which;
+use Archive::Tar::Streamed;
+use Algorithm::Diff;
+use Getopt::Std;
+use File::Slurp;
+
+my $bpc = BackupPC::Lib->new || die "can't create BackupPC::Lib";
+my %Conf = $bpc->Conf();
+
+use BackupPC::SearchLib;
+%BackupPC::SearchLib::Conf = %Conf;
 
 my $path = abs_path($0);
 $path =~ s#/[^/]+$#/#;
@@ -19,19 +29,23 @@ my $tarIncCreate = $path .= 'BackupPC_tarIncCreate';
 
 die "can't find $tarIncCreate: $!\n" unless (-x $tarIncCreate);
 
-my $debug = 1;
+my $bin;
+foreach my $c (qw/gzip md5sum/) {
+       $bin->{$c} = which($c) || die "$0 needs $c, install it\n";
+}
+
+my %opt;
+getopts("cd", \%opt );
+
+my $debug = $opt{d};
+my $check = $opt{c} && print STDERR "NOTICE: tar archive check forced\n";
+
 $|=1;
 
 my $start_t = time();
 
 my $t_fmt = '%Y-%m-%d %H:%M:%S';
 
-my $hosts;
-my $bpc = BackupPC::Lib->new || die;
-my %Conf = $bpc->Conf();
-my $TopDir = $bpc->TopDir();
-my $beenThere = {};
-
 my $dsn = $Conf{SearchDSN} || die "Need SearchDSN in config.pl\n";
 my $user = $Conf{SearchUser} || '';
 
@@ -56,39 +70,251 @@ sub curr_time {
        return strftime($t_fmt,localtime());
 }
 
+my $hsn_cache;
+
+sub get_backup_id($$$) {
+       my ($host, $share, $num) = @_;
+
+       my $key = "$host $share $num";
+       return $hsn_cache->{$key} if ($hsn_cache->{$key});
+
+       my $sth = $dbh->prepare(qq{
+               SELECT 
+                       backups.id
+               FROM backups 
+               INNER JOIN shares       ON backups.shareID=shares.ID
+               INNER JOIN hosts        ON backups.hostID = hosts.ID
+               where hosts.name = ? and shares.name = ? and backups.num = ?
+       });
+       $sth->execute($host, $share, $num);
+       my ($id) = $sth->fetchrow_array;
+
+       $hsn_cache->{"$host $share $num"} = $id;
+
+       print STDERR "# $host $share $num == $id\n" if ($opt{d});
+
+       return $id;
+}
+
+
+sub tar_check($$$$) {
+       my ($host,$share,$num,$filename) = @_;
+
+       sub check_part {
+               my ($host, $share, $num, $part_nr, $tar_size, $size, $md5, $items) = @_;
+               my $backup_id = get_backup_id($host, $share, $num);
+               my $sth_md5 = $dbh->prepare(qq{
+                       select
+                               id, tar_size, size, md5, items
+                       from backup_parts
+                       where backup_id = ? and part_nr = ?
+               });
+
+               $sth_md5->execute($backup_id, $part_nr);
+
+               if (my $row = $sth_md5->fetchrow_hashref) {
+                       return if (
+                               $row->{tar_size} >= $tar_size &&
+                               $row->{size} == $size &&
+                               $row->{md5} eq $md5 &&
+                               $row->{items} == $items
+                       );
+                       print STDERR "# deleting invalid row $row->{id}\n" if ($opt{d});
+                       $dbh->do(qq{ delete from backup_parts where id = $row->{id} });
+               }
+               print STDERR "# inserting new backup_part row\n";
+               my $sth_insert = $dbh->prepare(qq{
+                       insert into backup_parts (
+                               backup_id,
+                               part_nr,
+                               tar_size,
+                               size,
+                               md5,
+                               items
+                       ) values (?,?,?,?,?,?)
+               });
+
+               $sth_insert->execute($backup_id, $part_nr, $tar_size, $size, $md5, $items);
+               $dbh->commit;
+       }
+
+       if ($debug) {
+               print STDERR " {{ CHECK: ${host}:${share}#${num} and $filename";
+       } else {
+               print " check";
+       }
+
+       my @tar_parts;
+
+       if (-d "$tar_dir/$filename") {
+               print STDERR " multi-part" if ($opt{d});
+               opendir(my $dir, "$tar_dir/$filename") || die "can't readdir $tar_dir/$filename: $!";
+               @tar_parts = map { my $p = $_; $p =~ s#^#${filename}/#; $p } grep { !/^\./ && !/md5/ && -f "$tar_dir/$filename/$_" } readdir($dir);
+               closedir($dir);
+       } else {
+               push @tar_parts, "${filename}.tar.gz";
+       }
+
+       print " [parts: ",join(", ", @tar_parts),"]" if ($opt{d});
+
+       my $same = 1;
+       my @tar_files;
+
+       my $backup_part;
+
+       print " reading";
+
+       foreach my $tarfilename (@tar_parts) {
+
+               print STDERR " $tarfilename" if ($debug);
+
+               my $path = "$tar_dir/$tarfilename";
+               my $md5_path = $path;
+               $md5_path =~ s/\.tar\.gz$/.md5/ || die "can't create md5 filename from $md5_path";
+               if (! -e $md5_path || -z $md5_path) {
+                       print ", creating md5";
+                       system( $bin->{md5sum} . " $path > $md5_path") == 0 or die "can't create md5 $path: $!";
+               }
+
+               my $md5 = read_file( $md5_path ) || die "can't read md5sum file $md5_path: $!";
+               $md5 =~ s#\s.*$##;
+
+               my $part_nr = 1;
+               $part_nr = $1 if ($tarfilename =~ m#/(\d+)\.tar\.gz#);
+
+               my $size = (stat( "$tar_dir/$tarfilename" ))[7] || die "can't stat $tar_dir/$tarfilename";
+
+               open(my $fh, "gzip -cd $tar_dir/$tarfilename |") or die "can't open $tar_dir/$tarfilename: $!";
+               binmode($fh);
+               my $tar = Archive::Tar::Streamed->new($fh);
+
+               my $tar_size = 0;
+               my $items = 0;
+
+               while(my $entry = $tar->next) {
+                       push @tar_files, $entry->name;
+                       $items++;
+                       $tar_size += $entry->size;
+               }
+
+               if ($tar_size > $Conf{MaxArchiveFileSize}) {
+                       print STDERR " part too big $tar_size > $Conf{MaxArchiveFileSize} }}" if ($debug);
+                       $same = 0;
+                       last;
+               } elsif ($size > $Conf{MaxArchiveSize}) {
+                       print STDERR " part bigger than media $size > $Conf{MaxArchiveSize} }}" if ($debug);
+                       $same = 0;
+                       last;
+               }
+
+               check_part($host, $share, $num, $part_nr, $tar_size, $size, $md5, $items);
+       }
+
+       # short-cut and exit;
+       return $same unless($same);
+
+       @tar_files = sort @tar_files;
+       print STDERR " ",($#tar_files + 1), " files" if ($debug);
+
+       print STDERR ", database" if ($debug);
+
+       my $sth = $dbh->prepare(qq{
+               SELECT path,type
+               FROM files
+               JOIN shares on shares.id = shareid
+               JOIN hosts on hosts.id = shares.hostid
+               WHERE hosts.name = ? and shares.name = ? and backupnum = ?
+       });
+       $sth->execute($host, $share, $num);
+       my @db_files;
+       while( my $row = $sth->fetchrow_hashref ) {
+
+               my $path = $row->{'path'} || die "no path?";
+               $path =~ s#^/#./#;
+               $path .= '/' if ($row->{'type'} == BPC_FTYPE_DIR);
+               push @db_files, $path;
+       }
+
+       print STDERR " ",($#db_files + 1), " files, diff" if ($debug);
+
+       @db_files = sort @db_files;
+
+       if ($#tar_files != $#db_files) {
+               $same = 0;
+               print STDERR " NUMBER" if ($debug);
+       } else {
+               my $diff = Algorithm::Diff->new(\@tar_files, \@db_files);
+               while ( $diff->Next() ) {
+                       next if $diff->Same();
+                       $same = 0;
+                       print "< $_\n" for $diff->Items(1);
+                       print "> $_\n" for $diff->Items(2);
+               }
+       }
+
+       print " ",($same ? 'ok' : 'DIFFERENT');
+       print STDERR " }} " if ($debug);
+
+       return $same;
+}
+
+
 #----- main
 
 my $sth = $dbh->prepare( qq{
        
 select
+       backups.id as backup_id,
        hosts.name as host,
        shares.name as share,
-       num as num
+       backups.num as num,
+       inc_size,
+       parts
 from backups
        join shares on backups.hostid = shares.hostid
                and shares.id = backups.shareid
        join hosts on shares.hostid = hosts.id
-where inc_size < 0 and not inc_deleted
+where not inc_deleted
 order by backups.date
 
 } );
 
 $sth->execute();
-
-%BackupPC::SearchLib::Conf = %Conf;
+my $num_backups = $sth->rows;
+my $curr_backup = 1;
 
 while (my $row = $sth->fetchrow_hashref) {
        my $tar_file = BackupPC::SearchLib::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'});
-       print curr_time, sprintf(" %s:%s %-3d ", $row->{'host'}, $row->{'share'}, $row->{'num'}), " -> $tar_file ";
+
+       # this will return -1 if file doesn't exist
+       my $size = BackupPC::SearchLib::get_tgz_size_by_name($tar_file);
+
+       print "# size: $size backup.size: ", $row->{inc_size},"\n" if ($opt{d});
+
+       if ( $row->{'inc_size'} != -1 && $size != -1 && $row->{'inc_size'} >= $size) {
+               if ($check) {
+                       tar_check($row->{'host'}, $row->{'share'}, $row->{'num'}, $tar_file) && next;
+               } else {
+                       next;
+               }
+       }
+
+       print curr_time, " $curr_backup/$num_backups ", $row->{'host'}, ":", $row->{'share'}, " #", $row->{'num'}, " -> $tar_file";
+       $curr_backup++;
 
        my $t = time();
 
-       my $cmd = qq{$tarIncCreate -h "$row->{'host'}" -s "$row->{'share'}" -n $row->{'num'} | gzip -9 > $tar_dir/$tar_file};
+       # re-create archive?
+       my $cmd = qq{ $tarIncCreate -h "$row->{'host'}" -s "$row->{'share'}" -n $row->{'num'} -f };
        print STDERR "## $cmd\n" if ($debug);
 
-       system($cmd) == 0 or die "failed: $?";
+       if (system($cmd) != 0) {
+               print STDERR " FAILED";
+       }
+
+       print ", dur: ",fmt_time(time() - $t), "\n";
 
-       print fmt_time(time() - $t),"\n";
+       $dbh->commit;
 
 }