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