begin search integration into version 3.2.0
[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     #
249     # Prune deleted files
250     #
251     foreach my $file ( keys(%{$m->{files}}) ) {
252         next if ( $m->{files}{$file}{type} != BPC_FTYPE_DELETED );
253         delete($m->{files}{$file});
254     }
255     #print STDERR "Returning:\n", Dumper($m->{files});
256 }
257
258 #
259 # Return list of shares for this backup
260 #
261 sub shareList
262 {
263     my($m, $backupNum) = @_;
264     my @shareList;
265
266     $m->backupNumCache($backupNum) if ( $m->{num} != $backupNum );
267     return if ( $m->{idx} < 0 );
268
269     my $mangle = $m->{backups}[$m->{idx}]{mangle};
270     my $path = "$m->{topDir}/pc/$m->{host}/$backupNum/";
271     return if ( !opendir(DIR, $path) );
272     my @dir = readdir(DIR);
273     closedir(DIR);
274     foreach my $file ( @dir ) {
275         $file = $1 if ( $file =~ /(.*)/s );
276         next if ( $file eq "attrib" && $mangle
277                || $file eq "."
278                || $file eq ".."
279                || $file eq "backupInfo"
280             );
281         my $fileUM = $file;
282         $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
283         push(@shareList, $fileUM);
284     }
285     $m->{dir} = undef;
286     return @shareList;
287 }
288
289 sub backupNumCache
290 {
291     my($m, $backupNum) = @_;
292
293     if ( $m->{num} != $backupNum ) {
294         my $i;
295         for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
296             last if ( $m->{backups}[$i]{num} == $backupNum );
297         }
298         if ( $i >= @{$m->{backups}} ) {
299             $m->{idx} = -1;
300             return;
301         }
302         $m->{num} = $backupNum;
303         $m->{idx} = $i;
304     }
305 }
306
307 #
308 # Return the attributes of a specific file
309 #
310 sub fileAttrib
311 {
312     my($m, $backupNum, $share, $path) = @_;
313
314     #print(STDERR "fileAttrib($backupNum, $share, $path)\n");
315     if ( $path =~ s{(.*)/+(.+)}{$1}s ) {
316         my $file = $2;
317         $m->dirCache($backupNum, $share, $path);
318         return $m->{files}{$file};
319     } else {
320         #print STDERR "Got empty $path\n";
321         $m->dirCache($backupNum, "", "");
322         my $attr = $m->{files}{$share};
323         return if ( !defined($attr) );
324         $attr->{relPath} = "/";
325         return $attr;
326     }
327 }
328
329 #
330 # Return the contents of a directory
331 #
332 sub dirAttrib
333 {
334     my($m, $backupNum, $share, $dir) = @_;
335
336     $m->dirCache($backupNum, $share, $dir);
337     return $m->{files};
338 }
339
340 #
341 # Return a listref of backup numbers that are merged to create this view
342 #
343 sub mergeNums
344 {
345     my($m) = @_;
346
347     return $m->{mergeNums};
348 }
349
350 #
351 # Return a list of backup indexes for which the directory exists
352 #
353 sub backupList
354 {
355     my($m, $share, $dir) = @_;
356     my($i, @backupList);
357
358     $dir = "/$dir" if ( $dir !~ m{^/} );
359     $dir =~ s{/+$}{};
360
361     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
362         my $backupNum = $m->{backups}[$i]{num};
363         my $mangle = $m->{backups}[$i]{mangle};
364         my $path   = "$m->{topDir}/pc/$m->{host}/$backupNum/";
365         my $sharePathM;
366         if ( $mangle ) {
367             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
368                         . $m->{bpc}->fileNameMangle($dir);
369         } else {
370             $sharePathM = $share . $dir;
371         }
372         $path .= $sharePathM;
373         next if ( !-d $path );
374         push(@backupList, $i);
375     }
376     return @backupList;
377 }
378
379 #
380 # Return the history of all backups for a particular directory
381 #
382 sub dirHistory
383 {
384     my($m, $share, $dir) = @_;
385     my($i, $level);
386     my $files = {};
387
388     $dir = "/$dir" if ( $dir !~ m{^/} );
389     $dir =~ s{/+$}{};
390
391     #
392     # merge backups, starting at the first one, and working
393     # forward.
394     #
395     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
396         $level        = $m->{backups}[$i]{level};
397         my $backupNum = $m->{backups}[$i]{num};
398         my $mangle    = $m->{backups}[$i]{mangle};
399         my $compress  = $m->{backups}[$i]{compress};
400         my $path      = "$m->{topDir}/pc/$m->{host}/$backupNum/";
401         my $legacyCharset = $m->{backups}[$i]{version} < 3.0;
402         my $sharePathM;
403         if ( $mangle ) {
404             $sharePathM = $m->{bpc}->fileNameEltMangle($share)
405                         . $m->{bpc}->fileNameMangle($dir);
406         } else {
407             $sharePathM = $share . $dir;
408         }
409         $path .= $sharePathM;
410         #print(STDERR "Opening $path (share=$share)\n");
411
412         my $dirOpts    = { %{$m->{dirOpts} || {} } };
413         my $attribOpts = { compress => $compress };
414         if ( $legacyCharset ) {
415             $dirOpts->{charsetLegacy}
416                     = $attribOpts->{charsetLegacy}
417                     = $m->{bpc}->{Conf}{ClientCharsetLegacy} || "iso-8859-1";
418         }
419
420         my $dirInfo = $m->{bpc}->dirRead($path, $dirOpts);
421         if ( !defined($dirInfo) ) {
422             #
423             # Oops, directory doesn't exist.
424             #
425             next;
426         }
427         my $attr;
428         if ( $mangle ) {
429             $attr = BackupPC::Attrib->new($attribOpts);
430             if ( !$attr->read($path) ) {
431                 $m->{error} = "Can't read attribute file in $path";
432                 $attr = undef;
433             }
434         }
435         foreach my $entry ( @$dirInfo ) {
436             my $file = $1 if ( $entry->{name} =~ /(.*)/s );
437             my $fileUM = $file;
438             $fileUM = $m->{bpc}->fileNameUnmangle($fileUM) if ( $mangle );
439             #print(STDERR "Doing $fileUM\n");
440             #
441             # skip special files
442             #
443             next if (  $file eq ".."
444                     || $file eq "."
445                     || $mangle && $file eq "attrib"
446                     || defined($files->{$fileUM}[$i]) );
447
448             my $realPath = "$path/$file";
449             from_to($realPath, "utf8", $attribOpts->{charsetLegacy})
450                             if ( $attribOpts->{charsetLegacy} ne "" );
451             my @s = stat($realPath);
452             if ( defined($attr) && defined(my $a = $attr->get($fileUM)) ) {
453                 $files->{$fileUM}[$i] = $a;
454                 $attr->set($fileUM, undef);
455             } else {
456                 #
457                 # Very expensive in the non-attribute case when compresseion
458                 # is on.  We have to stat the file and read compressed files
459                 # to determine their size.
460                 #
461                 $files->{$fileUM}[$i] = {
462                     type  => -d _ ? BPC_FTYPE_DIR : BPC_FTYPE_FILE,
463                     mode  => $s[2],
464                     uid   => $s[4],
465                     gid   => $s[5],
466                     size  => -f _ ? $s[7] : 0,
467                     mtime => $s[9],
468                 };
469                 if ( $compress && -f _ ) {
470                     #
471                     # Compute the correct size by reading the whole file
472                     #
473                     my $f = BackupPC::FileZIO->open("$realPath",
474                                                     0, $compress);
475                     if ( !defined($f) ) {
476                         $m->{error} = "Can't open $path/$file";
477                     } else {
478                         my($data, $size);
479                         while ( $f->read(\$data, 65636 * 8) > 0 ) {
480                             $size += length($data);
481                         }
482                         $f->close;
483                         $files->{$fileUM}[$i]{size} = $size;
484                     }
485                 }
486             }
487             ($files->{$fileUM}[$i]{relPath}    = "$dir/$fileUM") =~ s{//+}{/}g;
488             ($files->{$fileUM}[$i]{sharePathM} = "$sharePathM/$file")
489                                                                 =~ s{//+}{/}g;
490             ($files->{$fileUM}[$i]{fullPath}   = "$path/$file") =~ s{//+}{/}g;
491             $files->{$fileUM}[$i]{backupNum}   = $backupNum;
492             $files->{$fileUM}[$i]{compress}    = $compress;
493             $files->{$fileUM}[$i]{nlink}       = $entry->{nlink}
494                                                     if ( $m->{dirOpts}{nlink} );
495             $files->{$fileUM}[$i]{inode}       = $entry->{inode}
496                                                     if ( $m->{dirOpts}{inode} );
497         }
498
499         #
500         # Flag deleted files
501         #
502         if ( defined($attr) ) {
503             my $a = $attr->get;
504             foreach my $fileUM ( keys(%$a) ) {
505                 next if ( $a->{$fileUM}{type} != BPC_FTYPE_DELETED );
506                 $files->{$fileUM}[$i]{type} = BPC_FTYPE_DELETED;
507             }
508         }
509
510         #
511         # Merge old backups.  Don't merge directories from old
512         # backups because every backup has an accurate directory
513         # tree.
514         #
515         for ( my $k = $i - 1 ; $level > 0 && $k >= 0 ; $k-- ) {
516             next if ( $m->{backups}[$k]{level} >= $level );
517             $level = $m->{backups}[$k]{level};
518             foreach my $fileUM ( keys(%$files) ) {
519                 next if ( !defined($files->{$fileUM}[$k])
520                         || defined($files->{$fileUM}[$i])
521                         || $files->{$fileUM}[$k]{type} == BPC_FTYPE_DIR );
522                 $files->{$fileUM}[$i] = $files->{$fileUM}[$k];
523             }
524         }
525     }
526
527     #
528     # Remove deleted files
529     #
530     for ( $i = 0 ; $i < @{$m->{backups}} ; $i++ ) {
531         foreach my $fileUM ( keys(%$files) ) {
532             next if ( !defined($files->{$fileUM}[$i])
533                     || $files->{$fileUM}[$i]{type} != BPC_FTYPE_DELETED );
534             $files->{$fileUM}[$i] = undef;
535         }
536     }
537
538     #print STDERR "Returning:\n", Dumper($files);
539     return $files;
540 }
541
542
543 #
544 # Do a recursive find starting at the given path (either a file
545 # or directory).  The callback function $callback is called on each
546 # file and directory.  The function arguments are the attrs hashref,
547 # and additional callback arguments.  The search is depth-first if
548 # depth is set.  Returns -1 if $path does not exist.
549 #
550 sub find
551 {
552     my($m, $backupNum, $share, $path, $depth, $callback, @callbackArgs) = @_;
553
554     #print(STDERR "find: got $backupNum, $share, $path\n");
555     #
556     # First call the callback on the given $path
557     #
558     my $attr = $m->fileAttrib($backupNum, $share, $path);
559     return -1 if ( !defined($attr) );
560     &$callback($attr, @callbackArgs);
561     return if ( $attr->{type} != BPC_FTYPE_DIR );
562
563     #
564     # Now recurse into subdirectories
565     #
566     $m->findRecurse($backupNum, $share, $path, $depth,
567                     $callback, @callbackArgs);
568 }
569
570 #
571 # Same as find(), except the callback is not called on the current
572 # $path, only on the contents of $path.  So if $path is a file then
573 # no callback or recursion occurs.
574 #
575 sub findRecurse
576 {
577     my($m, $backupNum, $share, $path, $depth, $callback, @callbackArgs) = @_;
578
579     my $attr = $m->dirAttrib($backupNum, $share, $path);
580     return if ( !defined($attr) );
581     foreach my $file ( sort(keys(%$attr)) ) {
582         &$callback($attr->{$file}, @callbackArgs);
583         next if ( !$depth || $attr->{$file}{type} != BPC_FTYPE_DIR );
584         #
585         # For depth-first, recurse as we hit each directory
586         #
587         $m->findRecurse($backupNum, $share, "$path/$file", $depth,
588                              $callback, @callbackArgs);
589     }
590     if ( !$depth ) {
591         #
592         # For non-depth, recurse directories after we finish current dir
593         #
594         foreach my $file ( keys(%{$attr}) ) {
595             next if ( $attr->{$file}{type} != BPC_FTYPE_DIR );
596             $m->findRecurse($backupNum, $share, "$path/$file", $depth,
597                             $callback, @callbackArgs);
598         }
599     }
600 }
601
602 1;