* checkin with 3.2.0beta0 release header
[BackupPC.git] / lib / BackupPC / PoolWrite.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::PoolWrite package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::PoolWrite class for writing
8 #   files to disk that are candidates for pooling.  One instance
9 #   of this class is used to write each file.  The following steps
10 #   are executed:
11 #
12 #     - As the incoming data arrives, the first 1MB is buffered
13 #       in memory so the MD5 digest can be computed.
14 #
15 #     - A running comparison against all the candidate pool files
16 #       (ie: those with the same MD5 digest, usually at most a single
17 #       file) is done as new incoming data arrives.  Up to $MaxFiles
18 #       simultaneous files can be compared in parallel.  This
19 #       involves reading and uncompressing one or more pool files.
20 #
21 #     - When a pool file no longer matches it is discarded from
22 #       the search.  If there are more than $MaxFiles candidates, one of
23 #       the new candidates is added to the search, first checking
24 #       that it matches up to the current point (this requires
25 #       re-reading one of the other pool files).
26 #
27 #     - When or if no pool files match then the new file is written
28 #       to disk.  This could occur many MB into the file.  We don't
29 #       need to buffer all this data in memory since we can copy it
30 #       from the last matching pool file, up to the point where it
31 #       fully matched.
32 #
33 #     - When all the new data is complete, if a pool file exactly
34 #       matches then the file is simply created as a hardlink to
35 #       the pool file.
36 #
37 # AUTHOR
38 #   Craig Barratt  <cbarratt@users.sourceforge.net>
39 #
40 # COPYRIGHT
41 #   Copyright (C) 2001-2007  Craig Barratt
42 #
43 #   This program is free software; you can redistribute it and/or modify
44 #   it under the terms of the GNU General Public License as published by
45 #   the Free Software Foundation; either version 2 of the License, or
46 #   (at your option) any later version.
47 #
48 #   This program is distributed in the hope that it will be useful,
49 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
50 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
51 #   GNU General Public License for more details.
52 #
53 #   You should have received a copy of the GNU General Public License
54 #   along with this program; if not, write to the Free Software
55 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
56 #
57 #========================================================================
58 #
59 # Version 3.2.0beta0, released 5 April 2009.
60 #
61 # See http://backuppc.sourceforge.net.
62 #
63 #========================================================================
64
65 package BackupPC::PoolWrite;
66
67 use strict;
68
69 use File::Path;
70 use Digest::MD5;
71 use BackupPC::FileZIO;
72
73 sub new
74 {
75     my($class, $bpc, $fileName, $fileSize, $compress) = @_;
76
77     my $self = bless {
78         fileName => $fileName,
79         fileSize => $fileSize,
80         bpc      => $bpc,
81         compress => $compress,
82         nWrite   => 0,
83         digest   => undef,
84         files    => [],
85         fileCnt  => -1,
86         fhOut    => undef,
87         errors   => [],
88         data     => "",
89         eof      => undef,
90     }, $class;
91
92     $self->{hardLinkMax} = $bpc->ConfValue("HardLinkMax");
93
94     #
95     # Always unlink any current file in case it is already linked
96     #
97     unlink($fileName) if ( -f $fileName );
98     if ( $fileName =~ m{(.*)/.+} && !-d $1 ) {
99         eval { mkpath($1, 0, 0777) };
100         if ( $@ ) {
101             push(@{$self->{errors}}, "Unable to create directory $1 for $self->{fileName}");
102         }
103     }
104     return $self;
105 }
106
107 my $BufSize  = 1048576;  # 1MB or 2^20
108 my $MaxFiles = 20;       # max number of compare files open at one time
109
110 sub write
111 {
112     my($a, $dataRef) = @_;
113
114     return if ( $a->{eof} );
115     $a->{data} .= $$dataRef if ( defined($dataRef) );
116     return if ( length($a->{data}) < $BufSize && defined($dataRef) );
117
118     #
119     # Correct the fileSize if it is wrong (rsync might transfer
120     # a file whose length is different to the length sent with the
121     # file list if the file changes between the file list sending
122     # and the file sending).  Here we only catch the case where
123     # we haven't computed the digest (ie: we have written no more
124     # than $BufSize).  We catch the big file case below.
125     #
126     if ( !defined($dataRef) && !defined($a->{digest})
127                 && $a->{fileSize} != length($a->{data}) ) {
128         #my $newSize = length($a->{data});
129         #print("Fixing file size from $a->{fileSize} to $newSize\n");
130         $a->{fileSize} = length($a->{data});
131     }
132
133     if ( !defined($a->{digest}) && length($a->{data}) > 0 ) {
134         #
135         # build a list of all the candidate matching files
136         #
137         my $md5 = Digest::MD5->new;
138         $a->{fileSize} = length($a->{data})
139                             if ( $a->{fileSize} < length($a->{data}) );
140         $a->{digest} = $a->{bpc}->Buffer2MD5($md5, $a->{fileSize}, \$a->{data});
141         if ( !defined($a->{base} = $a->{bpc}->MD52Path($a->{digest},
142                                                        $a->{compress})) ) {
143             push(@{$a->{errors}}, "Unable to get path from '$a->{digest}'"
144                                 . " for $a->{fileName}");
145         } else {
146             while ( @{$a->{files}} < $MaxFiles ) {
147                 my $fh;
148                 my $fileName = $a->{fileCnt} < 0 ? $a->{base}
149                                         : "$a->{base}_$a->{fileCnt}";
150                 last if ( !-f $fileName );
151                 #
152                 # Don't attempt to match pool files that already
153                 # have too many hardlinks.  Also, don't match pool
154                 # files with only one link since starting in
155                 # BackupPC v3.0, BackupPC_nightly could be running
156                 # in parallel (and removing those files).  This doesn't
157                 # eliminate all possible race conditions, but just
158                 # reduces the odds.  Other design steps eliminate
159                 # the remaining race conditions of linking vs
160                 # removing.
161                 #
162                 if ( (stat(_))[3] >= $a->{hardLinkMax}
163                     || (stat(_))[3] <= 1
164                     || !defined($fh = BackupPC::FileZIO->open($fileName, 0,
165                                                      $a->{compress})) ) {
166                     $a->{fileCnt}++;
167                     next;
168                 }
169                 push(@{$a->{files}}, {
170                         name => $fileName,
171                         fh   => $fh,
172                      });
173                 $a->{fileCnt}++;
174             }
175         }
176         #
177         # if there are no candidate files then we must write
178         # the new file to disk
179         #
180         if ( !@{$a->{files}} ) {
181             $a->{fhOut} = BackupPC::FileZIO->open($a->{fileName},
182                                               1, $a->{compress});
183             if ( !defined($a->{fhOut}) ) {
184                 push(@{$a->{errors}}, "Unable to open $a->{fileName}"
185                                     . " for writing");
186             }
187         }
188     }
189     my $dataLen = length($a->{data});
190     if ( !defined($a->{fhOut}) && length($a->{data}) > 0 ) {
191         #
192         # See if the new chunk of data continues to match the
193         # candidate files.
194         #
195         for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
196             my($d, $match);
197             my $fileName = $a->{fileCnt} < 0 ? $a->{base}
198                                              : "$a->{base}_$a->{fileCnt}";
199             if ( $dataLen > 0 ) {
200                 # verify next $dataLen bytes from candidate file
201                 my $n = $a->{files}[$i]->{fh}->read(\$d, $dataLen);
202                 next if ( $n == $dataLen && $d eq $a->{data} );
203             } else {
204                 # verify candidate file is at EOF
205                 my $n = $a->{files}[$i]->{fh}->read(\$d, 100);
206                 next if ( $n == 0 );
207             }
208             #print("   File $a->{files}[$i]->{name} doesn't match\n");
209             #
210             # this candidate file didn't match.  Replace it
211             # with a new candidate file.  We have to qualify
212             # any new candidate file by making sure that its
213             # first $a->{nWrite} bytes match, plus the next $dataLen
214             # bytes match $a->{data}.
215             #
216             while ( -f $fileName ) {
217                 my $fh;
218                 if ( (stat(_))[3] >= $a->{hardLinkMax}
219                     || !defined($fh = BackupPC::FileZIO->open($fileName, 0,
220                                                      $a->{compress})) ) {
221                     $a->{fileCnt}++;
222                     #print("   Discarding $fileName (open failed)\n");
223                     $fileName = "$a->{base}_$a->{fileCnt}";
224                     next;
225                 }
226                 if ( !$a->{files}[$i]->{fh}->rewind() ) {
227                     push(@{$a->{errors}},
228                             "Unable to rewind $a->{files}[$i]->{name}"
229                           . " for compare");
230                 }
231                 $match = $a->filePartialCompare($a->{files}[$i]->{fh}, $fh,
232                                           $a->{nWrite}, $dataLen, \$a->{data});
233                 if ( $match ) {
234                     $a->{files}[$i]->{fh}->close();
235                     $a->{files}[$i]->{fh} = $fh,
236                     $a->{files}[$i]->{name} = $fileName;
237                     #print("   Found new candidate $fileName\n");
238                     $a->{fileCnt}++;
239                     last;
240                 } else {
241                     #print("   Discarding $fileName (no match)\n");
242                 }
243                 $fh->close();
244                 $a->{fileCnt}++;
245                 $fileName = "$a->{base}_$a->{fileCnt}";
246             }
247             if ( !$match ) {
248                 #
249                 # We couldn't find another candidate file
250                 #
251                 if ( @{$a->{files}} == 1 ) {
252                     #print("   Exhausted matches, now writing\n");
253                     $a->{fhOut} = BackupPC::FileZIO->open($a->{fileName},
254                                                     1, $a->{compress});
255                     if ( !defined($a->{fhOut}) ) {
256                         push(@{$a->{errors}},
257                                 "Unable to open $a->{fileName}"
258                               . " for writing");
259                     } else {
260                         if ( !$a->{files}[$i]->{fh}->rewind() ) {
261                             push(@{$a->{errors}}, 
262                                      "Unable to rewind"
263                                    . " $a->{files}[$i]->{name} for copy");
264                         }
265                         $a->filePartialCopy($a->{files}[$i]->{fh}, $a->{fhOut},
266                                         $a->{nWrite});
267                     }
268                 }
269                 $a->{files}[$i]->{fh}->close();
270                 splice(@{$a->{files}}, $i, 1);
271                 $i--;
272             }
273         }
274     }
275     if ( defined($a->{fhOut}) && $dataLen > 0 ) {
276         #
277         # if we are in writing mode then just write the data
278         #
279         my $n = $a->{fhOut}->write(\$a->{data});
280         if ( $n != $dataLen ) {
281             push(@{$a->{errors}}, "Unable to write $dataLen bytes to"
282                                 . " $a->{fileName} (got $n)");
283         }
284     }
285     $a->{nWrite} += $dataLen;
286     $a->{data} = "";
287     return if ( defined($dataRef) );
288
289     #
290     # We are at EOF, so finish up
291     #
292     $a->{eof} = 1;
293
294     #
295     # Make sure the fileSize was correct.  See above for comments about
296     # rsync.
297     #
298     if ( $a->{nWrite} != $a->{fileSize} ) {
299         #
300         # Oops, fileSize was wrong, so our MD5 digest was wrong and our
301         # effort to match files likely failed.  This is ugly, but our
302         # only choice at this point is to re-write the entire file with
303         # the correct length.  We need to rename the file, open it for
304         # reading, and then re-write the file with the correct length.
305         #
306
307         #print("Doing big file fixup ($a->{fileSize} != $a->{nWrite})\n");
308
309         my($fh, $fileName);
310         $a->{fileSize} = $a->{nWrite};
311
312         if ( defined($a->{fhOut}) ) {
313             if ( $a->{fileName} =~ /(.*)\// ) {
314                 $fileName = $1;
315             } else {
316                 $fileName = ".";
317             }
318             #
319             # Find a unique target temporary file name
320             #
321             my $i = 0;
322             while ( -f "$fileName/t$$.$i" ) {
323                 $i++;
324             }
325             $fileName = "$fileName/t$$.$i";
326             $a->{fhOut}->close();
327             if ( !rename($a->{fileName}, $fileName)
328               || !defined($fh = BackupPC::FileZIO->open($fileName, 0,
329                                                  $a->{compress})) ) {
330                 push(@{$a->{errors}}, "Can't rename $a->{fileName} -> $fileName"
331                                     . " or open during size fixup");
332             }
333             #print("Using temporary name $fileName\n");
334         } elsif ( defined($a->{files}) && defined($a->{files}[0]) ) {
335             #
336             # We haven't written anything yet, so just use the
337             # compare file to copy from.
338             #
339             $fh = $a->{files}[0]->{fh};
340             $fh->rewind;
341             #print("Using compare file $a->{files}[0]->{name}\n");
342         }
343         if ( defined($fh) ) {
344             my $poolWrite = BackupPC::PoolWrite->new($a->{bpc}, $a->{fileName},
345                                         $a->{fileSize}, $a->{compress});
346             my $nRead = 0;
347
348             while ( $nRead < $a->{fileSize} ) {
349                 my $thisRead = $a->{fileSize} - $nRead < $BufSize
350                              ? $a->{fileSize} - $nRead : $BufSize;
351                 my $data;
352                 my $n = $fh->read(\$data, $thisRead);
353                 if ( $n != $thisRead ) {
354                     push(@{$a->{errors}},
355                                 "Unable to read $thisRead bytes during resize"
356                                . " from temp $fileName (got $n)");
357                     last;
358                 }
359                 $poolWrite->write(\$data);
360                 $nRead += $thisRead;
361             }
362             $fh->close;
363             unlink($fileName) if ( defined($fileName) );
364             if ( @{$a->{errors}} ) {
365                 $poolWrite->close;
366                 return (0, $a->{digest}, -s $a->{fileName}, $a->{errors});
367             } else {
368                 return $poolWrite->close;
369             }
370         }
371     }
372
373     if ( $a->{fileSize} == 0 ) {
374         #
375         # Simply create an empty file
376         #
377         local(*OUT);
378         if ( !open(OUT, ">", $a->{fileName}) ) {
379             push(@{$a->{errors}}, "Can't open $a->{fileName} for empty"
380                                 . " output");
381         } else {
382             close(OUT);
383         }
384         #
385         # Close the compare files
386         #
387         foreach my $f ( @{$a->{files}} ) {
388             $f->{fh}->close();
389         }
390         return (1, $a->{digest}, -s $a->{fileName}, $a->{errors});
391     } elsif ( defined($a->{fhOut}) ) {
392         $a->{fhOut}->close();
393         #
394         # Close the compare files
395         #
396         foreach my $f ( @{$a->{files}} ) {
397             $f->{fh}->close();
398         }
399         return (0, $a->{digest}, -s $a->{fileName}, $a->{errors});
400     } else {
401         if ( @{$a->{files}} == 0 ) {
402             push(@{$a->{errors}}, "Botch, no matches on $a->{fileName}"
403                                 . " ($a->{digest})");
404         } elsif ( @{$a->{files}} > 1 ) {
405             #
406             # This is no longer a real error because $Conf{HardLinkMax}
407             # could be hit, thereby creating identical pool files
408             #
409             #my $str = "Unexpected multiple matches on"
410             #       . " $a->{fileName} ($a->{digest})\n";
411             #for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
412             #    $str .= "     -> $a->{files}[$i]->{name}\n";
413             #}
414             #push(@{$a->{errors}}, $str);
415         }
416         for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
417             if ( link($a->{files}[$i]->{name}, $a->{fileName}) ) {
418                 #print("  Linked $a->{fileName} to $a->{files}[$i]->{name}\n");
419                 #
420                 # Close the compare files
421                 #
422                 foreach my $f ( @{$a->{files}} ) {
423                     $f->{fh}->close();
424                 }
425                 return (1, $a->{digest}, -s $a->{fileName}, $a->{errors});
426             }
427         }
428         #
429         # We were unable to link to the pool.  Either we're at the
430         # hardlink max, or the pool file got deleted.  Recover by
431         # writing the matching file, since we still have an open
432         # handle.
433         #
434         for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
435             if ( !$a->{files}[$i]->{fh}->rewind() ) {
436                 push(@{$a->{errors}}, 
437                          "Unable to rewind $a->{files}[$i]->{name}"
438                        . " for copy after link fail");
439                 next;
440             }
441             $a->{fhOut} = BackupPC::FileZIO->open($a->{fileName},
442                                             1, $a->{compress});
443             if ( !defined($a->{fhOut}) ) {
444                 push(@{$a->{errors}},
445                         "Unable to open $a->{fileName}"
446                       . " for writing after link fail");
447             } else {
448                 $a->filePartialCopy($a->{files}[$i]->{fh}, $a->{fhOut},
449                                     $a->{nWrite});
450                 $a->{fhOut}->close;
451             }
452             last;
453         }
454         #
455         # Close the compare files
456         #
457         foreach my $f ( @{$a->{files}} ) {
458             $f->{fh}->close();
459         }
460         return (0, $a->{digest}, -s $a->{fileName}, $a->{errors});
461     }
462 }
463
464 #
465 # Finish writing: pass undef dataRef to write so it can do all
466 # the work.  Returns a 4 element array:
467 #
468 #   (existingFlag, digestString, outputFileLength, errorList)
469 #
470 sub close
471 {
472     my($a) = @_;
473
474     return $a->write(undef);
475 }
476
477 #
478 # Abort a pool write
479 #
480 sub abort
481 {
482     my($a) = @_;
483
484     if ( defined($a->{fhOut}) ) {
485         $a->{fhOut}->close();
486         unlink($a->{fileName});
487     }
488     foreach my $f ( @{$a->{files}} ) {
489         $f->{fh}->close();
490     }
491     $a->{files} = [];
492 }
493
494 #
495 # Copy $nBytes from files $fhIn to $fhOut.
496 #
497 sub filePartialCopy
498 {
499     my($a, $fhIn, $fhOut, $nBytes) = @_;
500     my($nRead);
501
502     while ( $nRead < $nBytes ) {
503         my $thisRead = $nBytes - $nRead < $BufSize
504                             ? $nBytes - $nRead : $BufSize;
505         my $data;
506         my $n = $fhIn->read(\$data, $thisRead);
507         if ( $n != $thisRead ) {
508             push(@{$a->{errors}},
509                         "Unable to read $thisRead bytes from "
510                        . $fhIn->name . " (got $n)");
511             return;
512         }
513         $n = $fhOut->write(\$data, $thisRead);
514         if ( $n != $thisRead ) {
515             push(@{$a->{errors}},
516                         "Unable to write $thisRead bytes to "
517                        . $fhOut->name . " (got $n)");
518             return;
519         }
520         $nRead += $thisRead;
521     }
522 }
523
524 #
525 # Compare $nBytes from files $fh0 and $fh1, and also compare additional
526 # $extra bytes from $fh1 to $$extraData.
527 #
528 sub filePartialCompare
529 {
530     my($a, $fh0, $fh1, $nBytes, $extra, $extraData) = @_;
531     my($nRead, $n);
532     my($data0, $data1);
533
534     while ( $nRead < $nBytes ) {
535         my $thisRead = $nBytes - $nRead < $BufSize
536                             ? $nBytes - $nRead : $BufSize;
537         $n = $fh0->read(\$data0, $thisRead);
538         if ( $n != $thisRead ) {
539             push(@{$a->{errors}}, "Unable to read $thisRead bytes from "
540                                  . $fh0->name . " (got $n)");
541             return;
542         }
543         $n = $fh1->read(\$data1, $thisRead);
544         return 0 if ( $n < $thisRead || $data0 ne $data1 );
545         $nRead += $thisRead;
546     }
547     if ( $extra > 0 ) {
548         # verify additional bytes
549         $n = $fh1->read(\$data1, $extra);
550         return 0 if ( $n != $extra || $data1 ne $$extraData );
551     } else {
552         # verify EOF
553         $n = $fh1->read(\$data1, 100);
554         return 0 if ( $n != 0 );
555     }
556     return 1;
557 }
558
559 #
560 # LinkOrCopy() does a hardlink from oldFile to newFile.
561 #
562 # If that fails (because there are too many links on oldFile)
563 # then oldFile is copied to newFile, and the pool stats are
564 # returned to be added to the new file list.  That allows
565 # BackupPC_link to try again, and to create a new pool file
566 # if necessary.
567 #
568 sub LinkOrCopy
569 {
570     my($bpc, $oldFile, $oldFileComp, $newFile, $newFileComp) = @_;
571     my($nRead, $data);
572
573     unlink($newFile)  if ( -f $newFile );
574     #
575     # Try to link if hardlink limit is ok, and compression types
576     # are the same
577     #
578     return (1, undef) if ( (stat($oldFile))[3] < $bpc->{Conf}{HardLinkMax}
579                             && !$oldFileComp == !$newFileComp
580                             && link($oldFile, $newFile) );
581     #
582     # There are too many links on oldFile, or compression
583     # type if different, so now we have to copy it.
584     #
585     # We need to compute the file size, which is expensive
586     # since we need to read the file twice.  That's probably
587     # ok since the hardlink limit is rarely hit.
588     #
589     my $readFd = BackupPC::FileZIO->open($oldFile, 0, $oldFileComp);
590     if ( !defined($readFd) ) {
591         return (0, undef, undef, undef, ["LinkOrCopy: can't open $oldFile"]);
592     }
593     while ( $readFd->read(\$data, $BufSize) > 0 ) {
594         $nRead += length($data);
595     }
596     $readFd->rewind();
597
598     my $poolWrite = BackupPC::PoolWrite->new($bpc, $newFile,
599                                              $nRead, $newFileComp);
600     while ( $readFd->read(\$data, $BufSize) > 0 ) {
601         $poolWrite->write(\$data);
602     }
603     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
604
605     return ($exists, $digest, $nRead, $outSize, $errs);
606 }
607
608 1;