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