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