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