* Added some performance improvements to BackupPC::Xfer::RsyncFileIO
[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-2003  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.0.0, released 28 Jan 2007.
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
50 sub new
51 {
52     my($class, $bpc, $host, $backups, $options) = @_;
53     my $m = bless {
54         bpc       => $bpc,      # BackupPC::Lib object
55         host      => $host,     # host name
56         backups   => $backups,  # all backups for this host
57         num       => -1,        # backup number
58         idx       => -1,        # index into backups for backup
59                                 #   we are viewing
60         dirPath   => undef,     # path to current directory
61         dirAttr   => undef,     # attributes of current directory
62         dirOpts   => $options,  # $options is a hash of file attributes we need:
63                                 # type, inode, or nlink.  If set, these parameters
64                                 # are added to the returned hash.
65                                 # See BackupPC::Lib::dirRead().
66     }, $class;
67     for ( my $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
68         next if ( defined($m->{backups}[$i]{level}) );
69         $m->{backups}[$i]{level} = $m->{backups}[$i]{type} eq "incr" ? 1 : 0;
70     }
71     $m->{topDir} = $m->{bpc}->TopDir();
72     return $m;
73 }
74
75 sub dirCache
76 {
77     my($m, $backupNum, $share, $dir) = @_;
78     my($i, $level);
79
80     #print STDERR "dirCache($backupNum, $share, $dir)\n";
81     $dir = "/$dir" if ( $dir !~ m{^/} );
82     $dir =~ s{/+$}{};
83     return if ( $m->{num} == $backupNum
84                 && $m->{share} eq $share
85                 && defined($m->{dir})
86                 && $m->{dir} eq $dir );
87     $m->backupNumCache($backupNum) if ( $m->{num} != $backupNum );
88     return if ( $m->{idx} < 0 );
89
90     $m->{files} = {};
91     $level = $m->{backups}[$m->{idx}]{level} + 1;
92
93     #
94     # Remember the requested share and dir
95     #
96     $m->{share} = $share;
97     $m->{dir} = $dir;
98
99     #
100     # merge backups, starting at the requested one, and working
101     # backwards until we get to level 0.
102     #
103     $m->{mergeNums} = [];
104     for ( $i = $m->{idx} ; $level > 0 && $i >= 0 ; $i-- ) {
105         #print(STDERR "Do $i ($m->{backups}[$i]{noFill},$m->{backups}[$i]{level})\n");
106         #
107         # skip backups with the same or higher level
108         #
109         next if ( $m->{backups}[$i]{level} >= $level );
110
111         $level = $m->{backups}[$i]{level};
112         $backupNum = $m->{backups}[$i]{num};
113         push(@{$m->{mergeNums}}, $backupNum);
114         my $mangle   = $m->{backups}[$i]{mangle};
115         my $compress = $m->{backups}[$i]{compress};
116         my $path = "$m->{topDir}/pc/$m->{host}/$backupNum/";
117         my $sharePathM;
118         if ( $mangle ) {
119             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
120                         . $m->{bpc}->fileNameMangle($dir);
121         } else {
122             $sharePathM = $share . $dir;
123         }
124         $path .= $sharePathM;
125         #print(STDERR "Opening $path (share=$share)\n");
126
127         my $dirInfo = $m->{bpc}->dirRead($path, $m->{dirOpts});
128         if ( !defined($dirInfo) ) {
129             if ( $i == $m->{idx} ) {
130                 #
131                 # Oops, directory doesn't exist.
132                 #
133                 $m->{files} = undef;
134                 return;
135             }
136             next;
137         }
138         my $attr;
139         if ( $mangle ) {
140             $attr = BackupPC::Attrib->new({ compress => $compress });
141             if ( -f $attr->fileName($path) && !$attr->read($path) ) {
142                 $m->{error} = "Can't read attribute file in $path";
143                 $attr = undef;
144             }
145         }
146         foreach my $entry ( @$dirInfo ) {
147             my $file = $1 if ( $entry->{name} =~ /(.*)/s );
148             my $fileUM = $file;
149             $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
150             #print(STDERR "Doing $fileUM\n");
151             #
152             # skip special files
153             #
154             next if ( defined($m->{files}{$fileUM})
155                     || $file eq ".."
156                     || $file eq "."
157                     || $file eq "backupInfo"
158                     || $mangle && $file eq "attrib" );
159             if ( defined($attr) && defined(my $a = $attr->get($fileUM)) ) {
160                 $m->{files}{$fileUM} = $a;
161                 #
162                 # skip directories in earlier backups (each backup always
163                 # has the complete directory tree).
164                 #
165                 next if ( $i < $m->{idx} && $a->{type} == BPC_FTYPE_DIR );
166                 $attr->set($fileUM, undef);
167             } else {
168                 #
169                 # Very expensive in the non-attribute case when compresseion
170                 # is on.  We have to stat the file and read compressed files
171                 # to determine their size.
172                 #
173                 my @s = stat("$path/$file");
174                 next if ( $i < $m->{idx} && -d _ );
175                 $m->{files}{$fileUM} = {
176                     type  => -d _ ? BPC_FTYPE_DIR : BPC_FTYPE_FILE,
177                     mode  => $s[2],
178                     uid   => $s[4],
179                     gid   => $s[5],
180                     size  => -f _ ? $s[7] : 0,
181                     mtime => $s[9],
182                 };
183                 if ( $compress && -f _ ) {
184                     #
185                     # Compute the correct size by reading the whole file
186                     #
187                     my $f = BackupPC::FileZIO->open("$path/$file",
188                                                     0, $compress);
189                     if ( !defined($f) ) {
190                         $m->{error} = "Can't open $path/$file";
191                     } else {
192                         my($data, $size);
193                         while ( $f->read(\$data, 65636 * 8) > 0 ) {
194                             $size += length($data);
195                         }
196                         $f->close;
197                         $m->{files}{$fileUM}{size} = $size;
198                     }
199                 }
200             }
201             ($m->{files}{$fileUM}{relPath}    = "$dir/$fileUM") =~ s{//+}{/}g;
202             ($m->{files}{$fileUM}{sharePathM} = "$sharePathM/$file")
203                                                                =~ s{//+}{/}g;
204             ($m->{files}{$fileUM}{fullPath}   = "$path/$file") =~ s{//+}{/}g;
205             $m->{files}{$fileUM}{backupNum}   = $backupNum;
206             $m->{files}{$fileUM}{compress}    = $compress;
207             $m->{files}{$fileUM}{nlink}       = $entry->{nlink}
208                                                     if ( $m->{dirOpts}{nlink} );
209             $m->{files}{$fileUM}{inode}       = $entry->{inode}
210                                                     if ( $m->{dirOpts}{inode} );
211         }
212         #
213         # Also include deleted files
214         #
215         if ( defined($attr) ) {
216             my $a = $attr->get;
217             foreach my $fileUM ( keys(%$a) ) {
218                 next if ( $a->{$fileUM}{type} != BPC_FTYPE_DELETED );
219                 my $file = $fileUM;
220                 $file = $m->{bpc}->fileNameMangle($fileUM) if ( $mangle );
221                 $m->{files}{$fileUM}             = $a->{$fileUM};
222                 $m->{files}{$fileUM}{relPath}    = "$dir/$fileUM";
223                 $m->{files}{$fileUM}{sharePathM} = "$sharePathM/$file";
224                 $m->{files}{$fileUM}{fullPath}   = "$path/$file";
225                 $m->{files}{$fileUM}{backupNum}  = $backupNum;
226                 $m->{files}{$fileUM}{compress}   = $compress;
227                 $m->{files}{$fileUM}{nlink}      = 0;
228                 $m->{files}{$fileUM}{inode}      = 0;
229             }
230         }
231     }
232     #
233     # Prune deleted files
234     #
235     foreach my $file ( keys(%{$m->{files}}) ) {
236         next if ( $m->{files}{$file}{type} != BPC_FTYPE_DELETED );
237         delete($m->{files}{$file});
238     }
239     #print STDERR "Returning:\n", Dumper($m->{files});
240 }
241
242 #
243 # Return list of shares for this backup
244 #
245 sub shareList
246 {
247     my($m, $backupNum) = @_;
248     my @shareList;
249
250     $m->backupNumCache($backupNum) if ( $m->{num} != $backupNum );
251     return if ( $m->{idx} < 0 );
252
253     my $mangle = $m->{backups}[$m->{idx}]{mangle};
254     my $path = "$m->{topDir}/pc/$m->{host}/$backupNum/";
255     return if ( !opendir(DIR, $path) );
256     my @dir = readdir(DIR);
257     closedir(DIR);
258     foreach my $file ( @dir ) {
259         $file = $1 if ( $file =~ /(.*)/s );
260         next if ( $file eq "attrib" && $mangle
261                || $file eq "."
262                || $file eq ".."
263                || $file eq "backupInfo"
264             );
265         my $fileUM = $file;
266         $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
267         push(@shareList, $fileUM);
268     }
269     $m->{dir} = undef;
270     return @shareList;
271 }
272
273 sub backupNumCache
274 {
275     my($m, $backupNum) = @_;
276
277     if ( $m->{num} != $backupNum ) {
278         my $i;
279         for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
280             last if ( $m->{backups}[$i]{num} == $backupNum );
281         }
282         if ( $i >= @{$m->{backups}} ) {
283             $m->{idx} = -1;
284             return;
285         }
286         $m->{num} = $backupNum;
287         $m->{idx} = $i;
288     }
289 }
290
291 #
292 # Return the attributes of a specific file
293 #
294 sub fileAttrib
295 {
296     my($m, $backupNum, $share, $path) = @_;
297
298     #print(STDERR "fileAttrib($backupNum, $share, $path)\n");
299     if ( $path =~ s{(.*)/+(.+)}{$1}s ) {
300         my $file = $2;
301         $m->dirCache($backupNum, $share, $path);
302         return $m->{files}{$file};
303     } else {
304         #print STDERR "Got empty $path\n";
305         $m->dirCache($backupNum, "", "");
306         my $attr = $m->{files}{$share};
307         return if ( !defined($attr) );
308         $attr->{relPath} = "/";
309         return $attr;
310     }
311 }
312
313 #
314 # Return the contents of a directory
315 #
316 sub dirAttrib
317 {
318     my($m, $backupNum, $share, $dir) = @_;
319
320     $m->dirCache($backupNum, $share, $dir);
321     return $m->{files};
322 }
323
324 #
325 # Return a listref of backup numbers that are merged to create this view
326 #
327 sub mergeNums
328 {
329     my($m) = @_;
330
331     return $m->{mergeNums};
332 }
333
334 #
335 # Return a list of backup indexes for which the directory exists
336 #
337 sub backupList
338 {
339     my($m, $share, $dir) = @_;
340     my($i, @backupList);
341
342     $dir = "/$dir" if ( $dir !~ m{^/} );
343     $dir =~ s{/+$}{};
344
345     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
346         my $backupNum = $m->{backups}[$i]{num};
347         my $mangle = $m->{backups}[$i]{mangle};
348         my $path   = "$m->{topDir}/pc/$m->{host}/$backupNum/";
349         my $sharePathM;
350         if ( $mangle ) {
351             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
352                         . $m->{bpc}->fileNameMangle($dir);
353         } else {
354             $sharePathM = $share . $dir;
355         }
356         $path .= $sharePathM;
357         next if ( !-d $path );
358         push(@backupList, $i);
359     }
360     return @backupList;
361 }
362
363 #
364 # Return the history of all backups for a particular directory
365 #
366 sub dirHistory
367 {
368     my($m, $share, $dir) = @_;
369     my($i, $level);
370     my $files = {};
371
372     $dir = "/$dir" if ( $dir !~ m{^/} );
373     $dir =~ s{/+$}{};
374
375     #
376     # merge backups, starting at the first one, and working
377     # forward.
378     #
379     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
380         $level        = $m->{backups}[$i]{level};
381         my $backupNum = $m->{backups}[$i]{num};
382         my $mangle    = $m->{backups}[$i]{mangle};
383         my $compress  = $m->{backups}[$i]{compress};
384         my $path      = "$m->{topDir}/pc/$m->{host}/$backupNum/";
385         my $sharePathM;
386         if ( $mangle ) {
387             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
388                         . $m->{bpc}->fileNameMangle($dir);
389         } else {
390             $sharePathM = $share . $dir;
391         }
392         $path .= $sharePathM;
393         #print(STDERR "Opening $path (share=$share)\n");
394
395         my $dirInfo = $m->{bpc}->dirRead($path, $m->{dirOpts});
396         if ( !defined($dirInfo) ) {
397             #
398             # Oops, directory doesn't exist.
399             #
400             next;
401         }
402         my $attr;
403         if ( $mangle ) {
404             $attr = BackupPC::Attrib->new({ compress => $compress });
405             if ( -f $attr->fileName($path) && !$attr->read($path) ) {
406                 $m->{error} = "Can't read attribute file in $path";
407                 $attr = undef;
408             }
409         }
410         foreach my $entry ( @$dirInfo ) {
411             my $file = $1 if ( $entry->{name} =~ /(.*)/s );
412             my $fileUM = $file;
413             $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
414             #print(STDERR "Doing $fileUM\n");
415             #
416             # skip special files
417             #
418             next if (  $file eq ".."
419                     || $file eq "."
420                     || $mangle && $file eq "attrib"
421                     || defined($files->{$fileUM}[$i]) );
422             my @s = stat("$path/$file");
423             if ( defined($attr) && defined(my $a = $attr->get($fileUM)) ) {
424                 $files->{$fileUM}[$i] = $a;
425                 $attr->set($fileUM, undef);
426             } else {
427                 #
428                 # Very expensive in the non-attribute case when compresseion
429                 # is on.  We have to stat the file and read compressed files
430                 # to determine their size.
431                 #
432                 $files->{$fileUM}[$i] = {
433                     type  => -d _ ? BPC_FTYPE_DIR : BPC_FTYPE_FILE,
434                     mode  => $s[2],
435                     uid   => $s[4],
436                     gid   => $s[5],
437                     size  => -f _ ? $s[7] : 0,
438                     mtime => $s[9],
439                 };
440                 if ( $compress && -f _ ) {
441                     #
442                     # Compute the correct size by reading the whole file
443                     #
444                     my $f = BackupPC::FileZIO->open("$path/$file",
445                                                     0, $compress);
446                     if ( !defined($f) ) {
447                         $m->{error} = "Can't open $path/$file";
448                     } else {
449                         my($data, $size);
450                         while ( $f->read(\$data, 65636 * 8) > 0 ) {
451                             $size += length($data);
452                         }
453                         $f->close;
454                         $files->{$fileUM}[$i]{size} = $size;
455                     }
456                 }
457             }
458             ($files->{$fileUM}[$i]{relPath}    = "$dir/$fileUM") =~ s{//+}{/}g;
459             ($files->{$fileUM}[$i]{sharePathM} = "$sharePathM/$file")
460                                                                 =~ s{//+}{/}g;
461             ($files->{$fileUM}[$i]{fullPath}   = "$path/$file") =~ s{//+}{/}g;
462             $files->{$fileUM}[$i]{backupNum}   = $backupNum;
463             $files->{$fileUM}[$i]{compress}    = $compress;
464             $files->{$fileUM}[$i]{nlink}       = $entry->{nlink}
465                                                     if ( $m->{dirOpts}{nlink} );
466             $files->{$fileUM}[$i]{inode}       = $entry->{inode}
467                                                     if ( $m->{dirOpts}{inode} );
468         }
469
470         #
471         # Flag deleted files
472         #
473         if ( defined($attr) ) {
474             my $a = $attr->get;
475             foreach my $fileUM ( keys(%$a) ) {
476                 next if ( $a->{$fileUM}{type} != BPC_FTYPE_DELETED );
477                 $files->{$fileUM}[$i]{type} = BPC_FTYPE_DELETED;
478             }
479         }
480
481         #
482         # Merge old backups.  Don't merge directories from old
483         # backups because every backup has an accurate directory
484         # tree.
485         #
486         for ( my $k = $i - 1 ; $level > 0 && $k >= 0 ; $k-- ) {
487             next if ( $m->{backups}[$k]{level} >= $level );
488             $level = $m->{backups}[$k]{level};
489             foreach my $fileUM ( keys(%$files) ) {
490                 next if ( !defined($files->{$fileUM}[$k])
491                         || defined($files->{$fileUM}[$i])
492                         || $files->{$fileUM}[$k]{type} == BPC_FTYPE_DIR );
493                 $files->{$fileUM}[$i] = $files->{$fileUM}[$k];
494             }
495         }
496     }
497
498     #
499     # Remove deleted files
500     #
501     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
502         foreach my $fileUM ( keys(%$files) ) {
503             next if ( !defined($files->{$fileUM}[$i])
504                     || $files->{$fileUM}[$i]{type} != BPC_FTYPE_DELETED );
505             $files->{$fileUM}[$i] = undef;
506         }
507     }
508
509     #print STDERR "Returning:\n", Dumper($files);
510     return $files;
511 }
512
513
514 #
515 # Do a recursive find starting at the given path (either a file
516 # or directory).  The callback function $callback is called on each
517 # file and directory.  The function arguments are the attrs hashref,
518 # and additional callback arguments.  The search is depth-first if
519 # depth is set.  Returns -1 if $path does not exist.
520 #
521 sub find
522 {
523     my($m, $backupNum, $share, $path, $depth, $callback, @callbackArgs) = @_;
524
525     #print(STDERR "find: got $backupNum, $share, $path\n");
526     #
527     # First call the callback on the given $path
528     #
529     my $attr = $m->fileAttrib($backupNum, $share, $path);
530     return -1 if ( !defined($attr) );
531     &$callback($attr, @callbackArgs);
532     return if ( $attr->{type} != BPC_FTYPE_DIR );
533
534     #
535     # Now recurse into subdirectories
536     #
537     $m->findRecurse($backupNum, $share, $path, $depth,
538                     $callback, @callbackArgs);
539 }
540
541 #
542 # Same as find(), except the callback is not called on the current
543 # $path, only on the contents of $path.  So if $path is a file then
544 # no callback or recursion occurs.
545 #
546 sub findRecurse
547 {
548     my($m, $backupNum, $share, $path, $depth, $callback, @callbackArgs) = @_;
549
550     my $attr = $m->dirAttrib($backupNum, $share, $path);
551     return if ( !defined($attr) );
552     foreach my $file ( sort(keys(%$attr)) ) {
553         &$callback($attr->{$file}, @callbackArgs);
554         next if ( !$depth || $attr->{$file}{type} != BPC_FTYPE_DIR );
555         #
556         # For depth-first, recurse as we hit each directory
557         #
558         $m->findRecurse($backupNum, $share, "$path/$file", $depth,
559                              $callback, @callbackArgs);
560     }
561     if ( !$depth ) {
562         #
563         # For non-depth, recurse directories after we finish current dir
564         #
565         foreach my $file ( keys(%{$attr}) ) {
566             next if ( $attr->{$file}{type} != BPC_FTYPE_DIR );
567             $m->findRecurse($backupNum, $share, "$path/$file", $depth,
568                             $callback, @callbackArgs);
569         }
570     }
571 }
572
573 1;