re-implement only_increment by comparing inodes
[BackupPC.git] / lib / BackupPC / View.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::View package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::View class for merging of
8 #   incremental backups and file attributes.  This provides the
9 #   caller with a single view of a merged backup, without worrying
10 #   about which backup contributes which files.
11 #
12 # AUTHOR
13 #   Craig Barratt  <cbarratt@users.sourceforge.net>
14 #
15 # COPYRIGHT
16 #   Copyright (C) 2002-2009  Craig Barratt
17 #
18 #   This program is free software; you can redistribute it and/or modify
19 #   it under the terms of the GNU General Public License as published by
20 #   the Free Software Foundation; either version 2 of the License, or
21 #   (at your option) any later version.
22 #
23 #   This program is distributed in the hope that it will be useful,
24 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
25 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26 #   GNU General Public License for more details.
27 #
28 #   You should have received a copy of the GNU General Public License
29 #   along with this program; if not, write to the Free Software
30 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
31 #
32 #========================================================================
33 #
34 # Version 3.2.0, released 31 Jul 2010.
35 #
36 # See http://backuppc.sourceforge.net.
37 #
38 #========================================================================
39
40 package BackupPC::View;
41
42 use strict;
43
44 use File::Path;
45 use BackupPC::Lib;
46 use BackupPC::Attrib qw(:all);
47 use BackupPC::FileZIO;
48 use Data::Dumper;
49 use Encode qw/from_to/;
50
51 use Data::Dump qw(dump);
52
53 sub new
54 {
55     my($class, $bpc, $host, $backups, $options) = @_;
56     my $m = bless {
57         bpc       => $bpc,      # BackupPC::Lib object
58         host      => $host,     # host name
59         backups   => $backups,  # all backups for this host
60         num       => -1,        # backup number
61         idx       => -1,        # index into backups for backup
62                                 #   we are viewing
63         dirPath   => undef,     # path to current directory
64         dirAttr   => undef,     # attributes of current directory
65         dirOpts   => $options,  # $options is a hash of file attributes we need:
66                                 # type, inode, or nlink.  If set, these parameters
67                                 # are added to the returned hash.
68                                 # See BackupPC::Lib::dirRead().
69     }, $class;
70     $m->{topDir} = $m->{bpc}->TopDir();
71     return $m;
72 }
73
74 sub dirCache
75 {
76     my($m, $backupNum, $share, $dir) = @_;
77     my($i, $level);
78
79     print STDERR "dirCache($backupNum, $share, $dir)\n";
80     $dir = "/$dir" if ( $dir !~ m{^/} );
81     $dir =~ s{/+$}{};
82     return if ( $m->{num} == $backupNum
83                 && $m->{share} eq $share
84                 && defined($m->{dir})
85                 && $m->{dir} eq $dir );
86     $m->backupNumCache($backupNum) if ( $m->{num} != $backupNum );
87     return if ( $m->{idx} < 0 );
88
89     $m->{files} = {};
90     $level = $m->{backups}[$m->{idx}]{level} + 1;
91
92     #
93     # Remember the requested share and dir
94     #
95     $m->{share} = $share;
96     $m->{dir} = $dir;
97
98     my $previous_increment_entry;
99     my $increment_backupNum = $backupNum; # used in loop
100
101     #
102     # merge backups, starting at the requested one, and working
103     # backwards until we get to level 0.
104     #
105     $m->{mergeNums} = [];
106     for ( $i = $m->{idx} ; $level > 0 && $i >= 0 ; $i-- ) {
107         #print(STDERR "Do $i ($m->{backups}[$i]{noFill},$m->{backups}[$i]{level})\n");
108         #
109         # skip backups with the same or higher level
110         #
111         #next if ( $m->{backups}[$i]{level} >= $level );
112         # FIXME ASA skip all but first?
113
114         $level = $m->{backups}[$i]{level};
115         $backupNum = $m->{backups}[$i]{num};
116         push(@{$m->{mergeNums}}, $backupNum);
117         my $mangle   = $m->{backups}[$i]{mangle};
118         my $compress = $m->{backups}[$i]{compress};
119         my $path     = "$m->{topDir}/pc/$m->{host}/$backupNum/";
120         my $legacyCharset = $m->{backups}[$i]{version} < 3.0;
121         my $sharePathM;
122         if ( $mangle ) {
123             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
124                         . $m->{bpc}->fileNameMangle($dir);
125         } else {
126             $sharePathM = $share . $dir;
127         }
128         $path .= $sharePathM;
129         #print(STDERR "Opening $path (share=$share, mangle=$mangle)\n");
130
131         my $dirOpts    = { %{$m->{dirOpts} || {} } };
132         $dirOpts->{inode} = 1 if $m->{dirOpts}->{only_increment}; # ASA - detect unchanged
133 #warn "# dirOpts = ",dump $dirOpts;
134         my $attribOpts = { compress => $compress };
135         if ( $legacyCharset ) {
136             $dirOpts->{charsetLegacy}
137                     = $attribOpts->{charsetLegacy}
138                     = $m->{bpc}->{Conf}{ClientCharsetLegacy} || "iso-8859-1";
139         }
140
141         my $dirInfo = $m->{bpc}->dirRead($path, $dirOpts);
142         if ( !defined($dirInfo) ) {
143             if ( $i == $m->{idx} ) {
144                 #
145                 # Oops, directory doesn't exist.
146                 #
147                 $m->{files} = undef;
148                 return;
149             }
150             next;
151         }
152         my $attr;
153         if ( $mangle ) {
154             $attr = BackupPC::Attrib->new($attribOpts);
155             if ( !$attr->read($path) ) {
156                 $m->{error} = "Can't read attribute file in $path: " . $attr->errStr();
157                 $attr = undef;
158             }
159         }
160         foreach my $entry ( @$dirInfo ) {
161             my $file = $1 if ( $entry->{name} =~ /(.*)/s );
162             my $fileUM = $file;
163             $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
164             #print(STDERR "Doing $fileUM\n");
165             #
166             # skip special files
167             #
168             next if ( 0 # defined($m->{files}{$fileUM}) # ASA - need fallthrough
169                     || $file eq ".."
170                     || $file eq "."
171                     || $file eq "backupInfo"
172                     || $mangle && $file eq "attrib" );
173
174
175                 # ASA - we only skip files when invoked with share name
176                 if ( $m->{dirOpts}->{only_increment} && $share ) {
177                         if ( defined $previous_increment_entry->{$fileUM}
178                         && $previous_increment_entry->{$fileUM}->{inode} == $entry->{inode} ) {
179                                 warn "# -- $backupNum $fileUM\n";
180                                 $previous_increment_entry->{$fileUM}->{_hide}++;
181                                 next;
182                         } elsif ( $backupNum < $increment_backupNum ) {
183                                 warn "# << $backupNum $fileUM\n";
184                                 $previous_increment_entry->{$fileUM}->{_hide}++;
185                                 next;
186                         } else {
187                                 warn "# ++ $backupNum $fileUM ",dump $entry;
188                                 $previous_increment_entry->{$fileUM} = $entry;
189                         }
190                 } else {
191                         next if defined($m->{files}{$fileUM});
192                 }
193
194             if ( defined($attr) && defined(my $a = $attr->get($fileUM)) ) {
195                 $m->{files}{$fileUM} = $a;
196                 #
197                 # skip directories in earlier backups (each backup always
198                 # has the complete directory tree).
199                 #
200                 next if ( $i < $m->{idx} && $a->{type} == BPC_FTYPE_DIR );
201                 $attr->set($fileUM, undef);
202             } else {
203                 #
204                 # Very expensive in the non-attribute case when compresseion
205                 # is on.  We have to stat the file and read compressed files
206                 # to determine their size.
207                 #
208                 my $realPath = "$path/$file";
209
210                 from_to($realPath, "utf8", $attribOpts->{charsetLegacy})
211                                 if ( $attribOpts->{charsetLegacy} ne "" );
212
213                 my @s = stat($realPath);
214                 next if ( $i < $m->{idx} && -d _ );
215                 $m->{files}{$fileUM} = {
216                     type  => -d _ ? BPC_FTYPE_DIR : BPC_FTYPE_FILE,
217                     mode  => $s[2],
218                     uid   => $s[4],
219                     gid   => $s[5],
220                     size  => -f _ ? $s[7] : 0,
221                     mtime => $s[9],
222                 };
223                 if ( $compress && -f _ ) {
224                     #
225                     # Compute the correct size by reading the whole file
226                     #
227                     my $f = BackupPC::FileZIO->open($realPath,
228                                                     0, $compress);
229                     if ( !defined($f) ) {
230                         $m->{error} = "Can't open $realPath";
231                     } else {
232                         my($data, $size);
233                         while ( $f->read(\$data, 65636 * 8) > 0 ) {
234                             $size += length($data);
235                         }
236                         $f->close;
237                         $m->{files}{$fileUM}{size} = $size;
238                     }
239                 }
240             }
241             ($m->{files}{$fileUM}{relPath}    = "$dir/$fileUM") =~ s{//+}{/}g;
242             ($m->{files}{$fileUM}{sharePathM} = "$sharePathM/$file")
243                                                                =~ s{//+}{/}g;
244             ($m->{files}{$fileUM}{fullPath}   = "$path/$file") =~ s{//+}{/}g;
245             from_to($m->{files}{$fileUM}{fullPath}, "utf8", $attribOpts->{charsetLegacy})
246                                 if ( $attribOpts->{charsetLegacy} ne "" );
247             $m->{files}{$fileUM}{backupNum}   = $backupNum;
248             $m->{files}{$fileUM}{compress}    = $compress;
249             $m->{files}{$fileUM}{nlink}       = $entry->{nlink}
250                                                     if ( $m->{dirOpts}{nlink} );
251             $m->{files}{$fileUM}{inode}       = $entry->{inode}
252                                                     if ( $m->{dirOpts}{inode} );
253         }
254
255         #
256         # Also include deleted files
257         #
258         if ( defined($attr) ) {
259             my $a = $attr->get;
260             foreach my $fileUM ( keys(%$a) ) {
261                 next if ( $a->{$fileUM}{type} != BPC_FTYPE_DELETED );
262                 my $file = $fileUM;
263                 $file = $m->{bpc}->fileNameMangle($fileUM) if ( $mangle );
264                 $m->{files}{$fileUM}             = $a->{$fileUM};
265                 $m->{files}{$fileUM}{relPath}    = "$dir/$fileUM";
266                 $m->{files}{$fileUM}{sharePathM} = "$sharePathM/$file";
267                 $m->{files}{$fileUM}{fullPath}   = "$path/$file";
268                 from_to($m->{files}{$fileUM}{fullPath}, "utf8", $attribOpts->{charsetLegacy})
269                                     if ( $attribOpts->{charsetLegacy} ne "" );
270                 $m->{files}{$fileUM}{backupNum}  = $backupNum;
271                 $m->{files}{$fileUM}{compress}   = $compress;
272                 $m->{files}{$fileUM}{nlink}      = 0;
273                 $m->{files}{$fileUM}{inode}      = 0;
274             }
275         }
276     }
277
278         # ASA create increment
279         if ( $m->{dirOpts}->{only_increment} ) {
280                 warn "# previous_increment_entry = ",dump $previous_increment_entry;
281                 foreach my $file ( grep { exists $previous_increment_entry->{$_}->{_hide} } keys %$previous_increment_entry ) {
282                         delete $m->{files}{$file};
283                         warn "OLD $file\n";
284                 }
285         }
286
287     #
288     # Prune deleted files
289     #
290     foreach my $file ( keys(%{$m->{files}}) ) {
291         next if ( $m->{files}{$file}{type} != BPC_FTYPE_DELETED );
292         delete($m->{files}{$file});
293     }
294     #print STDERR "Returning:\n", Dumper($m->{files});
295 }
296
297 #
298 # Return list of shares for this backup
299 #
300 sub shareList
301 {
302     my($m, $backupNum) = @_;
303     my @shareList;
304
305     $m->backupNumCache($backupNum) if ( $m->{num} != $backupNum );
306     return if ( $m->{idx} < 0 );
307
308     my $mangle = $m->{backups}[$m->{idx}]{mangle};
309     my $path = "$m->{topDir}/pc/$m->{host}/$backupNum/";
310     return if ( !opendir(DIR, $path) );
311     my @dir = readdir(DIR);
312     closedir(DIR);
313     foreach my $file ( @dir ) {
314         $file = $1 if ( $file =~ /(.*)/s );
315         next if ( $file eq "attrib" && $mangle
316                || $file eq "."
317                || $file eq ".."
318                || $file eq "backupInfo"
319             );
320         my $fileUM = $file;
321         $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
322         push(@shareList, $fileUM);
323     }
324     $m->{dir} = undef;
325     return @shareList;
326 }
327
328 sub backupNumCache
329 {
330     my($m, $backupNum) = @_;
331
332     if ( $m->{num} != $backupNum ) {
333         my $i;
334         for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
335             last if ( $m->{backups}[$i]{num} == $backupNum );
336         }
337         if ( $i >= @{$m->{backups}} ) {
338             $m->{idx} = -1;
339             return;
340         }
341         $m->{num} = $backupNum;
342         $m->{idx} = $i;
343     }
344 }
345
346 #
347 # Return the attributes of a specific file
348 #
349 sub fileAttrib
350 {
351     my($m, $backupNum, $share, $path) = @_;
352
353     #print(STDERR "fileAttrib($backupNum, $share, $path)\n");
354     if ( $path =~ s{(.*)/+(.+)}{$1}s ) {
355         my $file = $2;
356         $m->dirCache($backupNum, $share, $path);
357         return $m->{files}{$file};
358     } else {
359         #print STDERR "Got empty $path\n";
360         $m->dirCache($backupNum, "", "");
361         my $attr = $m->{files}{$share};
362         return if ( !defined($attr) );
363         $attr->{relPath} = "/";
364         return $attr;
365     }
366 }
367
368 #
369 # Return the contents of a directory
370 #
371 sub dirAttrib
372 {
373     my($m, $backupNum, $share, $dir) = @_;
374
375     $m->dirCache($backupNum, $share, $dir);
376     return $m->{files};
377 }
378
379 #
380 # Return a listref of backup numbers that are merged to create this view
381 #
382 sub mergeNums
383 {
384     my($m) = @_;
385
386     return $m->{mergeNums};
387 }
388
389 #
390 # Return a list of backup indexes for which the directory exists
391 #
392 sub backupList
393 {
394     my($m, $share, $dir) = @_;
395     my($i, @backupList);
396
397     $dir = "/$dir" if ( $dir !~ m{^/} );
398     $dir =~ s{/+$}{};
399
400     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
401         my $backupNum = $m->{backups}[$i]{num};
402         my $mangle = $m->{backups}[$i]{mangle};
403         my $path   = "$m->{topDir}/pc/$m->{host}/$backupNum/";
404         my $sharePathM;
405         if ( $mangle ) {
406             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
407                         . $m->{bpc}->fileNameMangle($dir);
408         } else {
409             $sharePathM = $share . $dir;
410         }
411         $path .= $sharePathM;
412         next if ( !-d $path );
413         push(@backupList, $i);
414     }
415     return @backupList;
416 }
417
418 #
419 # Return the history of all backups for a particular directory
420 #
421 sub dirHistory
422 {
423     my($m, $share, $dir) = @_;
424     my($i, $level);
425     my $files = {};
426
427     $dir = "/$dir" if ( $dir !~ m{^/} );
428     $dir =~ s{/+$}{};
429
430     #
431     # merge backups, starting at the first one, and working
432     # forward.
433     #
434     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
435         $level        = $m->{backups}[$i]{level};
436         my $backupNum = $m->{backups}[$i]{num};
437         my $mangle    = $m->{backups}[$i]{mangle};
438         my $compress  = $m->{backups}[$i]{compress};
439         my $path      = "$m->{topDir}/pc/$m->{host}/$backupNum/";
440         my $legacyCharset = $m->{backups}[$i]{version} < 3.0;
441         my $sharePathM;
442         if ( $mangle ) {
443             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
444                         . $m->{bpc}->fileNameMangle($dir);
445         } else {
446             $sharePathM = $share . $dir;
447         }
448         $path .= $sharePathM;
449         #print(STDERR "Opening $path (share=$share)\n");
450
451         my $dirOpts    = { %{$m->{dirOpts} || {} } };
452         my $attribOpts = { compress => $compress };
453         if ( $legacyCharset ) {
454             $dirOpts->{charsetLegacy}
455                     = $attribOpts->{charsetLegacy}
456                     = $m->{bpc}->{Conf}{ClientCharsetLegacy} || "iso-8859-1";
457         }
458
459         my $dirInfo = $m->{bpc}->dirRead($path, $dirOpts);
460         if ( !defined($dirInfo) ) {
461             #
462             # Oops, directory doesn't exist.
463             #
464             next;
465         }
466         my $attr;
467         if ( $mangle ) {
468             $attr = BackupPC::Attrib->new($attribOpts);
469             if ( !$attr->read($path) ) {
470                 $m->{error} = "Can't read attribute file in $path";
471                 $attr = undef;
472             }
473         }
474         foreach my $entry ( @$dirInfo ) {
475             my $file = $1 if ( $entry->{name} =~ /(.*)/s );
476             my $fileUM = $file;
477             $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
478             #print(STDERR "Doing $fileUM\n");
479             #
480             # skip special files
481             #
482             next if (  $file eq ".."
483                     || $file eq "."
484                     || $mangle && $file eq "attrib"
485                     || defined($files->{$fileUM}[$i]) );
486
487             my $realPath = "$path/$file";
488             from_to($realPath, "utf8", $attribOpts->{charsetLegacy})
489                             if ( $attribOpts->{charsetLegacy} ne "" );
490             my @s = stat($realPath);
491             if ( defined($attr) && defined(my $a = $attr->get($fileUM)) ) {
492                 $files->{$fileUM}[$i] = $a;
493                 $attr->set($fileUM, undef);
494             } else {
495                 #
496                 # Very expensive in the non-attribute case when compresseion
497                 # is on.  We have to stat the file and read compressed files
498                 # to determine their size.
499                 #
500                 $files->{$fileUM}[$i] = {
501                     type  => -d _ ? BPC_FTYPE_DIR : BPC_FTYPE_FILE,
502                     mode  => $s[2],
503                     uid   => $s[4],
504                     gid   => $s[5],
505                     size  => -f _ ? $s[7] : 0,
506                     mtime => $s[9],
507                 };
508                 if ( $compress && -f _ ) {
509                     #
510                     # Compute the correct size by reading the whole file
511                     #
512                     my $f = BackupPC::FileZIO->open("$realPath",
513                                                     0, $compress);
514                     if ( !defined($f) ) {
515                         $m->{error} = "Can't open $path/$file";
516                     } else {
517                         my($data, $size);
518                         while ( $f->read(\$data, 65636 * 8) > 0 ) {
519                             $size += length($data);
520                         }
521                         $f->close;
522                         $files->{$fileUM}[$i]{size} = $size;
523                     }
524                 }
525             }
526             ($files->{$fileUM}[$i]{relPath}    = "$dir/$fileUM") =~ s{//+}{/}g;
527             ($files->{$fileUM}[$i]{sharePathM} = "$sharePathM/$file")
528                                                                 =~ s{//+}{/}g;
529             ($files->{$fileUM}[$i]{fullPath}   = "$path/$file") =~ s{//+}{/}g;
530             $files->{$fileUM}[$i]{backupNum}   = $backupNum;
531             $files->{$fileUM}[$i]{compress}    = $compress;
532             $files->{$fileUM}[$i]{nlink}       = $entry->{nlink}
533                                                     if ( $m->{dirOpts}{nlink} );
534             $files->{$fileUM}[$i]{inode}       = $entry->{inode}
535                                                     if ( $m->{dirOpts}{inode} );
536         }
537
538         #
539         # Flag deleted files
540         #
541         if ( defined($attr) ) {
542             my $a = $attr->get;
543             foreach my $fileUM ( keys(%$a) ) {
544                 next if ( $a->{$fileUM}{type} != BPC_FTYPE_DELETED );
545                 $files->{$fileUM}[$i]{type} = BPC_FTYPE_DELETED;
546             }
547         }
548
549         #
550         # Merge old backups.  Don't merge directories from old
551         # backups because every backup has an accurate directory
552         # tree.
553         #
554         for ( my $k = $i - 1 ; $level > 0 && $k >= 0 ; $k-- ) {
555             next if ( $m->{backups}[$k]{level} >= $level );
556             $level = $m->{backups}[$k]{level};
557             foreach my $fileUM ( keys(%$files) ) {
558                 next if ( !defined($files->{$fileUM}[$k])
559                         || defined($files->{$fileUM}[$i])
560                         || $files->{$fileUM}[$k]{type} == BPC_FTYPE_DIR );
561                 $files->{$fileUM}[$i] = $files->{$fileUM}[$k];
562             }
563         }
564     }
565
566     #
567     # Remove deleted files
568     #
569     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
570         foreach my $fileUM ( keys(%$files) ) {
571             next if ( !defined($files->{$fileUM}[$i])
572                     || $files->{$fileUM}[$i]{type} != BPC_FTYPE_DELETED );
573             $files->{$fileUM}[$i] = undef;
574         }
575     }
576
577     #print STDERR "Returning:\n", Dumper($files);
578     return $files;
579 }
580
581
582 #
583 # Do a recursive find starting at the given path (either a file
584 # or directory).  The callback function $callback is called on each
585 # file and directory.  The function arguments are the attrs hashref,
586 # and additional callback arguments.  The search is depth-first if
587 # depth is set.  Returns -1 if $path does not exist.
588 #
589 sub find
590 {
591     my($m, $backupNum, $share, $path, $depth, $callback, @callbackArgs) = @_;
592
593     #print(STDERR "find: got $backupNum, $share, $path\n");
594     #
595     # First call the callback on the given $path
596     #
597     my $attr = $m->fileAttrib($backupNum, $share, $path);
598     return -1 if ( !defined($attr) );
599     &$callback($attr, @callbackArgs);
600     return if ( $attr->{type} != BPC_FTYPE_DIR );
601
602     #
603     # Now recurse into subdirectories
604     #
605     $m->findRecurse($backupNum, $share, $path, $depth,
606                     $callback, @callbackArgs);
607 }
608
609 #
610 # Same as find(), except the callback is not called on the current
611 # $path, only on the contents of $path.  So if $path is a file then
612 # no callback or recursion occurs.
613 #
614 sub findRecurse
615 {
616     my($m, $backupNum, $share, $path, $depth, $callback, @callbackArgs) = @_;
617
618     my $attr = $m->dirAttrib($backupNum, $share, $path);
619     return if ( !defined($attr) );
620     foreach my $file ( sort(keys(%$attr)) ) {
621         &$callback($attr->{$file}, @callbackArgs);
622         next if ( !$depth || $attr->{$file}{type} != BPC_FTYPE_DIR );
623         #
624         # For depth-first, recurse as we hit each directory
625         #
626         $m->findRecurse($backupNum, $share, "$path/$file", $depth,
627                              $callback, @callbackArgs);
628     }
629     if ( !$depth ) {
630         #
631         # For non-depth, recurse directories after we finish current dir
632         #
633         foreach my $file ( keys(%{$attr}) ) {
634             next if ( $attr->{$file}{type} != BPC_FTYPE_DIR );
635             $m->findRecurse($backupNum, $share, "$path/$file", $depth,
636                             $callback, @callbackArgs);
637         }
638     }
639 }
640
641 1;