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