3.1.0 changes:
[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.1.0, released 25 Nov 2007.
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     return $self;
99 }
100
101 my $BufSize  = 1048576;  # 1MB or 2^20
102 my $MaxFiles = 20;       # max number of compare files open at one time
103
104 sub write
105 {
106     my($a, $dataRef) = @_;
107
108     return if ( $a->{eof} );
109     $a->{data} .= $$dataRef if ( defined($dataRef) );
110     return if ( length($a->{data}) < $BufSize && defined($dataRef) );
111
112     #
113     # Correct the fileSize if it is wrong (rsync might transfer
114     # a file whose length is different to the length sent with the
115     # file list if the file changes between the file list sending
116     # and the file sending).  Here we only catch the case where
117     # we haven't computed the digest (ie: we have written no more
118     # than $BufSize).  We catch the big file case below.
119     #
120     if ( !defined($dataRef) && !defined($a->{digest})
121                 && $a->{fileSize} != length($a->{data}) ) {
122         #my $newSize = length($a->{data});
123         #print("Fixing file size from $a->{fileSize} to $newSize\n");
124         $a->{fileSize} = length($a->{data});
125     }
126
127     if ( !defined($a->{digest}) && length($a->{data}) > 0 ) {
128         #
129         # build a list of all the candidate matching files
130         #
131         my $md5 = Digest::MD5->new;
132         $a->{fileSize} = length($a->{data})
133                             if ( $a->{fileSize} < length($a->{data}) );
134         $a->{digest} = $a->{bpc}->Buffer2MD5($md5, $a->{fileSize}, \$a->{data});
135         if ( !defined($a->{base} = $a->{bpc}->MD52Path($a->{digest},
136                                                        $a->{compress})) ) {
137             push(@{$a->{errors}}, "Unable to get path from '$a->{digest}'"
138                                 . " for $a->{fileName}\n");
139         } else {
140             while ( @{$a->{files}} < $MaxFiles ) {
141                 my $fh;
142                 my $fileName = $a->{fileCnt} < 0 ? $a->{base}
143                                         : "$a->{base}_$a->{fileCnt}";
144                 last if ( !-f $fileName );
145                 #
146                 # Don't attempt to match pool files that already
147                 # have too many hardlinks.  Also, don't match pool
148                 # files with only one link since starting in
149                 # BackupPC v3.0, BackupPC_nightly could be running
150                 # in parallel (and removing those files).  This doesn't
151                 # eliminate all possible race conditions, but just
152                 # reduces the odds.  Other design steps eliminate
153                 # the remaining race conditions of linking vs
154                 # removing.
155                 #
156                 if ( (stat(_))[3] >= $a->{hardLinkMax}
157                     || (stat(_))[3] <= 1
158                     || !defined($fh = BackupPC::FileZIO->open($fileName, 0,
159                                                      $a->{compress})) ) {
160                     $a->{fileCnt}++;
161                     next;
162                 }
163                 push(@{$a->{files}}, {
164                         name => $fileName,
165                         fh   => $fh,
166                      });
167                 $a->{fileCnt}++;
168             }
169         }
170         #
171         # if there are no candidate files then we must write
172         # the new file to disk
173         #
174         if ( !@{$a->{files}} ) {
175             $a->{fhOut} = BackupPC::FileZIO->open($a->{fileName},
176                                               1, $a->{compress});
177             if ( !defined($a->{fhOut}) ) {
178                 push(@{$a->{errors}}, "Unable to open $a->{fileName}"
179                                     . " for writing\n");
180             }
181         }
182     }
183     my $dataLen = length($a->{data});
184     if ( !defined($a->{fhOut}) && length($a->{data}) > 0 ) {
185         #
186         # See if the new chunk of data continues to match the
187         # candidate files.
188         #
189         for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
190             my($d, $match);
191             my $fileName = $a->{fileCnt} < 0 ? $a->{base}
192                                              : "$a->{base}_$a->{fileCnt}";
193             if ( $dataLen > 0 ) {
194                 # verify next $dataLen bytes from candidate file
195                 my $n = $a->{files}[$i]->{fh}->read(\$d, $dataLen);
196                 next if ( $n == $dataLen && $d eq $a->{data} );
197             } else {
198                 # verify candidate file is at EOF
199                 my $n = $a->{files}[$i]->{fh}->read(\$d, 100);
200                 next if ( $n == 0 );
201             }
202             #print("   File $a->{files}[$i]->{name} doesn't match\n");
203             #
204             # this candidate file didn't match.  Replace it
205             # with a new candidate file.  We have to qualify
206             # any new candidate file by making sure that its
207             # first $a->{nWrite} bytes match, plus the next $dataLen
208             # bytes match $a->{data}.
209             #
210             while ( -f $fileName ) {
211                 my $fh;
212                 if ( (stat(_))[3] >= $a->{hardLinkMax}
213                     || !defined($fh = BackupPC::FileZIO->open($fileName, 0,
214                                                      $a->{compress})) ) {
215                     $a->{fileCnt}++;
216                     #print("   Discarding $fileName (open failed)\n");
217                     $fileName = "$a->{base}_$a->{fileCnt}";
218                     next;
219                 }
220                 if ( !$a->{files}[$i]->{fh}->rewind() ) {
221                     push(@{$a->{errors}},
222                             "Unable to rewind $a->{files}[$i]->{name}"
223                           . " for compare\n");
224                 }
225                 $match = $a->filePartialCompare($a->{files}[$i]->{fh}, $fh,
226                                           $a->{nWrite}, $dataLen, \$a->{data});
227                 if ( $match ) {
228                     $a->{files}[$i]->{fh}->close();
229                     $a->{files}[$i]->{fh} = $fh,
230                     $a->{files}[$i]->{name} = $fileName;
231                     #print("   Found new candidate $fileName\n");
232                     $a->{fileCnt}++;
233                     last;
234                 } else {
235                     #print("   Discarding $fileName (no match)\n");
236                 }
237                 $fh->close();
238                 $a->{fileCnt}++;
239                 $fileName = "$a->{base}_$a->{fileCnt}";
240             }
241             if ( !$match ) {
242                 #
243                 # We couldn't find another candidate file
244                 #
245                 if ( @{$a->{files}} == 1 ) {
246                     #print("   Exhausted matches, now writing\n");
247                     $a->{fhOut} = BackupPC::FileZIO->open($a->{fileName},
248                                                     1, $a->{compress});
249                     if ( !defined($a->{fhOut}) ) {
250                         push(@{$a->{errors}},
251                                 "Unable to open $a->{fileName}"
252                               . " for writing\n");
253                     } else {
254                         if ( !$a->{files}[$i]->{fh}->rewind() ) {
255                             push(@{$a->{errors}}, 
256                                      "Unable to rewind"
257                                    . " $a->{files}[$i]->{name} for copy\n");
258                         }
259                         $a->filePartialCopy($a->{files}[$i]->{fh}, $a->{fhOut},
260                                         $a->{nWrite});
261                     }
262                 }
263                 $a->{files}[$i]->{fh}->close();
264                 splice(@{$a->{files}}, $i, 1);
265                 $i--;
266             }
267         }
268     }
269     if ( defined($a->{fhOut}) && $dataLen > 0 ) {
270         #
271         # if we are in writing mode then just write the data
272         #
273         my $n = $a->{fhOut}->write(\$a->{data});
274         if ( $n != $dataLen ) {
275             push(@{$a->{errors}}, "Unable to write $dataLen bytes to"
276                                 . " $a->{fileName} (got $n)\n");
277         }
278     }
279     $a->{nWrite} += $dataLen;
280     $a->{data} = "";
281     return if ( defined($dataRef) );
282
283     #
284     # We are at EOF, so finish up
285     #
286     $a->{eof} = 1;
287
288     #
289     # Make sure the fileSize was correct.  See above for comments about
290     # rsync.
291     #
292     if ( $a->{nWrite} != $a->{fileSize} ) {
293         #
294         # Oops, fileSize was wrong, so our MD5 digest was wrong and our
295         # effort to match files likely failed.  This is ugly, but our
296         # only choice at this point is to re-write the entire file with
297         # the correct length.  We need to rename the file, open it for
298         # reading, and then re-write the file with the correct length.
299         #
300
301         #print("Doing big file fixup ($a->{fileSize} != $a->{nWrite})\n");
302
303         my($fh, $fileName);
304         $a->{fileSize} = $a->{nWrite};
305
306         if ( defined($a->{fhOut}) ) {
307             if ( $a->{fileName} =~ /(.*)\// ) {
308                 $fileName = $1;
309             } else {
310                 $fileName = ".";
311             }
312             #
313             # Find a unique target temporary file name
314             #
315             my $i = 0;
316             while ( -f "$fileName/t$$.$i" ) {
317                 $i++;
318             }
319             $fileName = "$fileName/t$$.$i";
320             $a->{fhOut}->close();
321             if ( !rename($a->{fileName}, $fileName)
322               || !defined($fh = BackupPC::FileZIO->open($fileName, 0,
323                                                  $a->{compress})) ) {
324                 push(@{$a->{errors}}, "Can't rename $a->{fileName} -> $fileName"
325                                     . " or open during size fixup\n");
326             }
327             #print("Using temporary name $fileName\n");
328         } elsif ( defined($a->{files}) && defined($a->{files}[0]) ) {
329             #
330             # We haven't written anything yet, so just use the
331             # compare file to copy from.
332             #
333             $fh = $a->{files}[0]->{fh};
334             $fh->rewind;
335             #print("Using compare file $a->{files}[0]->{name}\n");
336         }
337         if ( defined($fh) ) {
338             my $poolWrite = BackupPC::PoolWrite->new($a->{bpc}, $a->{fileName},
339                                         $a->{fileSize}, $a->{compress});
340             my $nRead = 0;
341
342             while ( $nRead < $a->{fileSize} ) {
343                 my $thisRead = $a->{fileSize} - $nRead < $BufSize
344                              ? $a->{fileSize} - $nRead : $BufSize;
345                 my $data;
346                 my $n = $fh->read(\$data, $thisRead);
347                 if ( $n != $thisRead ) {
348                     push(@{$a->{errors}},
349                                 "Unable to read $thisRead bytes during resize"
350                                . " from temp $fileName (got $n)\n");
351                     last;
352                 }
353                 $poolWrite->write(\$data);
354                 $nRead += $thisRead;
355             }
356             $fh->close;
357             unlink($fileName) if ( defined($fileName) );
358             if ( @{$a->{errors}} ) {
359                 $poolWrite->close;
360                 return (0, $a->{digest}, -s $a->{fileName}, $a->{errors});
361             } else {
362                 return $poolWrite->close;
363             }
364         }
365     }
366
367     if ( $a->{fileSize} == 0 ) {
368         #
369         # Simply create an empty file
370         #
371         local(*OUT);
372         if ( !open(OUT, ">", $a->{fileName}) ) {
373             push(@{$a->{errors}}, "Can't open $a->{fileName} for empty"
374                                 . " output\n");
375         } else {
376             close(OUT);
377         }
378         #
379         # Close the compare files
380         #
381         foreach my $f ( @{$a->{files}} ) {
382             $f->{fh}->close();
383         }
384         return (1, $a->{digest}, -s $a->{fileName}, $a->{errors});
385     } elsif ( defined($a->{fhOut}) ) {
386         $a->{fhOut}->close();
387         #
388         # Close the compare files
389         #
390         foreach my $f ( @{$a->{files}} ) {
391             $f->{fh}->close();
392         }
393         return (0, $a->{digest}, -s $a->{fileName}, $a->{errors});
394     } else {
395         if ( @{$a->{files}} == 0 ) {
396             push(@{$a->{errors}}, "Botch, no matches on $a->{fileName}"
397                                 . " ($a->{digest})\n");
398         } elsif ( @{$a->{files}} > 1 ) {
399             #
400             # This is no longer a real error because $Conf{HardLinkMax}
401             # could be hit, thereby creating identical pool files
402             #
403             #my $str = "Unexpected multiple matches on"
404             #       . " $a->{fileName} ($a->{digest})\n";
405             #for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
406             #    $str .= "     -> $a->{files}[$i]->{name}\n";
407             #}
408             #push(@{$a->{errors}}, $str);
409         }
410         for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
411             if ( link($a->{files}[$i]->{name}, $a->{fileName}) ) {
412                 #print("  Linked $a->{fileName} to $a->{files}[$i]->{name}\n");
413                 #
414                 # Close the compare files
415                 #
416                 foreach my $f ( @{$a->{files}} ) {
417                     $f->{fh}->close();
418                 }
419                 return (1, $a->{digest}, -s $a->{fileName}, $a->{errors});
420             }
421         }
422         #
423         # We were unable to link to the pool.  Either we're at the
424         # hardlink max, or the pool file got deleted.  Recover by
425         # writing the matching file, since we still have an open
426         # handle.
427         #
428         for ( my $i = 0 ; $i < @{$a->{files}} ; $i++ ) {
429             if ( !$a->{files}[$i]->{fh}->rewind() ) {
430                 push(@{$a->{errors}}, 
431                          "Unable to rewind $a->{files}[$i]->{name}"
432                        . " for copy after link fail\n");
433                 next;
434             }
435             $a->{fhOut} = BackupPC::FileZIO->open($a->{fileName},
436                                             1, $a->{compress});
437             if ( !defined($a->{fhOut}) ) {
438                 push(@{$a->{errors}},
439                         "Unable to open $a->{fileName}"
440                       . " for writing after link fail\n");
441             } else {
442                 $a->filePartialCopy($a->{files}[$i]->{fh}, $a->{fhOut},
443                                     $a->{nWrite});
444                 $a->{fhOut}->close;
445             }
446             last;
447         }
448         #
449         # Close the compare files
450         #
451         foreach my $f ( @{$a->{files}} ) {
452             $f->{fh}->close();
453         }
454         return (0, $a->{digest}, -s $a->{fileName}, $a->{errors});
455     }
456 }
457
458 #
459 # Finish writing: pass undef dataRef to write so it can do all
460 # the work.  Returns a 4 element array:
461 #
462 #   (existingFlag, digestString, outputFileLength, errorList)
463 #
464 sub close
465 {
466     my($a) = @_;
467
468     return $a->write(undef);
469 }
470
471 #
472 # Abort a pool write
473 #
474 sub abort
475 {
476     my($a) = @_;
477
478     if ( defined($a->{fhOut}) ) {
479         $a->{fhOut}->close();
480         unlink($a->{fileName});
481     }
482     foreach my $f ( @{$a->{files}} ) {
483         $f->{fh}->close();
484     }
485     $a->{files} = [];
486 }
487
488 #
489 # Copy $nBytes from files $fhIn to $fhOut.
490 #
491 sub filePartialCopy
492 {
493     my($a, $fhIn, $fhOut, $nBytes) = @_;
494     my($nRead);
495
496     while ( $nRead < $nBytes ) {
497         my $thisRead = $nBytes - $nRead < $BufSize
498                             ? $nBytes - $nRead : $BufSize;
499         my $data;
500         my $n = $fhIn->read(\$data, $thisRead);
501         if ( $n != $thisRead ) {
502             push(@{$a->{errors}},
503                         "Unable to read $thisRead bytes from "
504                        . $fhIn->name . " (got $n)\n");
505             return;
506         }
507         $n = $fhOut->write(\$data, $thisRead);
508         if ( $n != $thisRead ) {
509             push(@{$a->{errors}},
510                         "Unable to write $thisRead bytes to "
511                        . $fhOut->name . " (got $n)\n");
512             return;
513         }
514         $nRead += $thisRead;
515     }
516 }
517
518 #
519 # Compare $nBytes from files $fh0 and $fh1, and also compare additional
520 # $extra bytes from $fh1 to $$extraData.
521 #
522 sub filePartialCompare
523 {
524     my($a, $fh0, $fh1, $nBytes, $extra, $extraData) = @_;
525     my($nRead, $n);
526     my($data0, $data1);
527
528     while ( $nRead < $nBytes ) {
529         my $thisRead = $nBytes - $nRead < $BufSize
530                             ? $nBytes - $nRead : $BufSize;
531         $n = $fh0->read(\$data0, $thisRead);
532         if ( $n != $thisRead ) {
533             push(@{$a->{errors}}, "Unable to read $thisRead bytes from "
534                                  . $fh0->name . " (got $n)\n");
535             return;
536         }
537         $n = $fh1->read(\$data1, $thisRead);
538         return 0 if ( $n < $thisRead || $data0 ne $data1 );
539         $nRead += $thisRead;
540     }
541     if ( $extra > 0 ) {
542         # verify additional bytes
543         $n = $fh1->read(\$data1, $extra);
544         return 0 if ( $n != $extra || $data1 ne $$extraData );
545     } else {
546         # verify EOF
547         $n = $fh1->read(\$data1, 100);
548         return 0 if ( $n != 0 );
549     }
550     return 1;
551 }
552
553 #
554 # LinkOrCopy() does a hardlink from oldFile to newFile.
555 #
556 # If that fails (because there are too many links on oldFile)
557 # then oldFile is copied to newFile, and the pool stats are
558 # returned to be added to the new file list.  That allows
559 # BackupPC_link to try again, and to create a new pool file
560 # if necessary.
561 #
562 sub LinkOrCopy
563 {
564     my($bpc, $oldFile, $oldFileComp, $newFile, $newFileComp) = @_;
565     my($nRead, $data);
566
567     unlink($newFile)  if ( -f $newFile );
568     #
569     # Try to link if hardlink limit is ok, and compression types
570     # are the same
571     #
572     return (1, undef) if ( (stat($oldFile))[3] < $bpc->{Conf}{HardLinkMax}
573                             && !$oldFileComp == !$newFileComp
574                             && link($oldFile, $newFile) );
575     #
576     # There are too many links on oldFile, or compression
577     # type if different, so now we have to copy it.
578     #
579     # We need to compute the file size, which is expensive
580     # since we need to read the file twice.  That's probably
581     # ok since the hardlink limit is rarely hit.
582     #
583     my $readFd = BackupPC::FileZIO->open($oldFile, 0, $oldFileComp);
584     if ( !defined($readFd) ) {
585         return (0, undef, undef, undef, ["LinkOrCopy: can't open $oldFile"]);
586     }
587     while ( $readFd->read(\$data, $BufSize) > 0 ) {
588         $nRead += length($data);
589     }
590     $readFd->rewind();
591
592     my $poolWrite = BackupPC::PoolWrite->new($bpc, $newFile,
593                                              $nRead, $newFileComp);
594     while ( $readFd->read(\$data, $BufSize) > 0 ) {
595         $poolWrite->write(\$data);
596     }
597     my($exists, $digest, $outSize, $errs) = $poolWrite->close;
598
599     return ($exists, $digest, $nRead, $outSize, $errs);
600 }
601
602 1;