2 #============================================================= -*-perl-*-
4 # BackupPC_tarIncCreate: create a tar archive of an existing incremental dump
9 # Usage: BackupPC_tarIncCreate [options]
14 # -h host Host from which the tar archive is created.
15 # -n dumpNum Dump number from which the tar archive is created.
16 # A negative number means relative to the end (eg -1
17 # means the most recent dump, -2 2nd most recent etc).
18 # -s shareName Share name from which the tar archive is created.
21 # -t print summary totals
22 # -r pathRemove path prefix that will be replaced with pathAdd
23 # -p pathAdd new path prefix
24 # -b BLOCKS BLOCKS x 512 bytes per record (default 20; same as tar)
25 # -w writeBufSz write buffer size (default 1MB)
27 # The -h, -n and -s options specify which dump is used to generate
28 # the tar archive. The -r and -p options can be used to relocate
29 # the paths in the tar archive so extracted files can be placed
30 # in a location different from their original location.
33 # Craig Barratt <cbarratt@users.sourceforge.net>
34 # Ivan Klaric <iklaric@gmail.com>
35 # Dobrica Pavlinusic <dpavlin@rot13.org>
38 # Copyright (C) 2001-2003 Craig Barratt
40 # This program is free software; you can redistribute it and/or modify
41 # it under the terms of the GNU General Public License as published by
42 # the Free Software Foundation; either version 2 of the License, or
43 # (at your option) any later version.
45 # This program is distributed in the hope that it will be useful,
46 # but WITHOUT ANY WARRANTY; without even the implied warranty of
47 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
48 # GNU General Public License for more details.
50 # You should have received a copy of the GNU General Public License
51 # along with this program; if not, write to the Free Software
52 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
54 #========================================================================
56 # Version 2.1.0, released 20 Jun 2004.
58 # See http://backuppc.sourceforge.net.
60 #========================================================================
64 use lib "__INSTALLDIR__/lib";
69 use BackupPC::Attrib qw(:all);
70 use BackupPC::FileZIO;
72 use BackupPC::SearchLib;
73 use Time::HiRes qw/time/;
74 use POSIX qw/strftime/;
78 use Data::Dumper; ### FIXME
80 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
81 my $TopDir = $bpc->TopDir();
82 my $BinDir = $bpc->BinDir();
83 my %Conf = $bpc->Conf();
84 %BackupPC::SearchLib::Conf = %Conf;
86 my $in_backup_increment;
89 if ( !getopts("th:n:p:r:s:b:w:vdf", \%opts) ) {
93 -h host host from which the tar archive is created
94 -n dumpNum dump number from which the tar archive is created
95 A negative number means relative to the end (eg -1
96 means the most recent dump, -2 2nd most recent etc).
97 -s shareName share name from which the tar archive is created
100 -t print summary totals
101 -r pathRemove path prefix that will be replaced with pathAdd
102 -p pathAdd new path prefix
103 -b BLOCKS BLOCKS x 512 bytes per record (default 20; same as tar)
104 -w writeBufSz write buffer size (default 1048576 = 1MB)
105 -f overwrite existing parts
112 if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
113 die "$0: bad host name '$opts{h}'\n";
117 if ( $opts{n} !~ /^(-?\d+)$/ ) {
118 die "$0: bad dump number '$opts{n}'\n";
123 foreach my $c (qw/gzip md5sum tee/) {
124 $bin->{$c} = which($c) || die "$0 needs $c, install it\n";
127 my @Backups = $bpc->BackupInfoRead($Host);
133 my $current_tar_size = 0;
134 my $total_increment_size = 0;
137 $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
138 for ( $i = 0 ; $i < @Backups ; $i++ ) {
139 last if ( $Backups[$i]{num} == $Num );
141 if ( $i >= @Backups ) {
142 die "$0: bad backup number $Num for host $Host\n";
145 my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
146 my $PathAdd = $1 if ( $opts{p} =~ /(.+)/ );
147 if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ && $opts{s} ne "*" ) {
148 die "$0: bad share name '$opts{s}'\n";
150 our $ShareName = $opts{s};
151 our $view = BackupPC::View->new($bpc, $Host, \@Backups);
155 my $dsn = $Conf{SearchDSN};
156 my $db_user = $Conf{SearchUser} || '';
158 my $dbh = DBI->connect($dsn, $db_user, "", { RaiseError => 1, AutoCommit => 0} );
160 my $sth_inc_size = $dbh->prepare(qq{
167 my $sth_backup_parts = $dbh->prepare(qq{
168 insert into backup_parts (
175 ) values (?,?,?,?,?,?)
179 # This constant and the line of code below that uses it are borrowed
180 # from Archive::Tar. Thanks to Calle Dybedahl and Stephen Zander.
183 # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
184 # Copyright 1998 Stephen Zander. All rights reserved.
187 = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
188 my $tar_header_length = 512;
190 my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
192 my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
194 my(%UidCache, %GidCache);
195 my(%HardLinkExtraFiles, @HardLinks);
198 # Write out all the requested files/directories
201 my $max_file_size = $Conf{'MaxArchiveFileSize'} || die "problem with MaxArchiveFileSize parametar";
203 my $tar_dir = $Conf{InstallDir}.'/'.$Conf{GzipTempDir};
204 die "problem with $tar_dir, check GzipTempDir in configuration\n" unless (-d $tar_dir && -w $tar_dir);
206 my $tar_file = BackupPC::SearchLib::getGzipName($Host, $ShareName, $Num) || die "can't getGzipName($Host, $ShareName, $Num)";
208 my $tar_path_final = $tar_dir . '/' . $tar_file;
209 my $tar_path = $tar_path_final . '.tmp';
211 $tar_path =~ s#//#/#g;
213 my $sth = $dbh->prepare(qq{
217 JOIN shares on shares.id = shareid
218 JOIN hosts on hosts.id = shares.hostid
219 WHERE hosts.name = ? and shares.name = ? and backups.num = ?
221 $sth->execute($Host, $ShareName, $Num);
222 my ($backup_id) = $sth->fetchrow_array;
226 # delete exising backup_parts
227 my $sth_delete_backup_parts = $dbh->prepare(qq{
228 delete from backup_parts
231 $sth_delete_backup_parts->execute($backup_id);
234 print STDERR "backup_id: $backup_id working dir: $tar_dir, max uncompressed size $max_file_size bytes, tar $tar_file\n" if ($opts{d});
236 if (-e $tar_path_final) {
238 rmtree $tar_path_final || die "can't remove $tar_path_final: $!";
240 die "$tar_path_final allready exists\n";
247 my $items_in_part = 0;
253 return if ($current_tar_size == 0);
255 print STDERR "\n\t+ $part:";
258 # Finish with two null 512 byte headers,
259 # and then round out a full block.
261 my $data = "\0" x ($tar_header_length * 2);
262 TarWrite($fh, \$data);
263 TarWrite($fh, undef);
265 close($fh) || die "can't close archive part $part: $!";
267 my $file = $tar_path . '/' . $part;
269 my $md5 = read_file( $file . '.md5' ) || die "can't read md5sum file ${file}.md5";
272 my $size = (stat( $file . '.tar.gz' ))[7] || die "can't stat ${file}.tar.gz";
274 print "$file, $size bytes, $items_in_part items";
276 $sth_backup_parts->execute(
285 $total_increment_size += $size;
291 print STDERR "# rename $from -> $to\n" if ($opts{d});
292 rename $from, $to || die "can't move $from -> $to: $!\n";
296 print STDERR " single" if ($opts{v});
297 move("${tar_path}/1.tar.gz", "${tar_path_final}.tar.gz");
298 move("${tar_path}/1.md5", "${tar_path_final}.md5");
299 rmtree $tar_path or die "can't remove temporary dir $tar_path: $!";
301 print STDERR " [last]" if ($opts{v});
302 move("${tar_path}", "${tar_path_final}");
304 # if this archive was single part, remove it
305 foreach my $suffix (qw/.tar.gz .md5/) {
306 my $path = $tar_path_final . $suffix;
307 unlink $path if (-e $path);
311 $sth_inc_size->execute(
312 $total_increment_size,
317 print "\n\ttotal $total_increment_size bytes";
326 # if this is first part, create directory
330 print STDERR "# deleting existing $tar_path\n" if ($opts{d});
333 mkdir($tar_path) || die "can't create directory $tar_path: $!";
336 print STDERR "ABORTED: cleanup temp dir";
342 $SIG{'INT'} = \&abort_cleanup;
343 $SIG{'QUIT'} = \&abort_cleanup;
344 $SIG{'__DIE__'} = \&abort_cleanup;
348 my $file = $tar_path . '/' . $part;
351 # create comprex pipe which will pass output through gzip
352 # for compression, create file on disk using tee
353 # and pipe same output to md5sum to create checksum
356 my $cmd = '| ' . $bin->{'gzip'} . ' ' . $Conf{GzipLevel} . ' ' .
357 '| ' . $bin->{'tee'} . ' ' . $file . '.tar.gz' . ' ' .
358 '| ' . $bin->{'md5sum'} . ' - > ' . $file . '.md5';
360 print STDERR "## $cmd\n" if ($opts{d});
362 open($fh, $cmd) or die "can't open $cmd: $!";
365 $current_tar_size = 0;
371 if (seedCache($Host, $ShareName, $Num)) {
372 archiveWrite($fh, '/');
373 archiveWriteHardLinks($fh);
374 new_tar_part( close => 1 );
376 print STDERR "NOTE: no files found for $Host:$ShareName, increment $Num\n" if ($opts{v});
377 # remove temporary files if there are no files
382 # print out totals if requested
385 print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
386 " $SpecialCnt specials, $ErrorCnt errors\n";
388 if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
390 # Got errors, with no files or directories; exit with non-zero
393 die "got errors or no files\n";
396 $sth_inc_size->finish;
397 $sth_backup_parts->finish;
399 $dbh->commit || die "can't commit changes to database";
404 ###########################################################################
406 ###########################################################################
410 my($fh, $dir, $tarPathOverride) = @_;
412 if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
413 print(STDERR "$0: bad directory '$dir'\n");
417 $dir = "/" if ( $dir eq "." );
418 #print(STDERR "calling find with $Num, $ShareName, $dir\n");
420 if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
421 $fh, $tarPathOverride) < 0 ) {
422 print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
429 # Write out any hardlinks (if any)
431 sub archiveWriteHardLinks
434 foreach my $hdr ( @HardLinks ) {
436 if ( defined($PathRemove)
437 && substr($hdr->{linkname}, 0, length($PathRemove)+1)
438 eq ".$PathRemove" ) {
439 substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
441 TarWriteFileInfo($fh, $hdr);
444 %HardLinkExtraFiles = ();
451 $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
452 return $UidCache{$uid};
459 $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
460 return $GidCache{$gid};
465 my($fh, $dataRef) = @_;
468 if ( !defined($dataRef) ) {
470 # do flush by padding to a full $WriteBufSz
472 my $data = "\0" x ($WriteBufSz - length($WriteBuf));
476 # poor man's tell :-)
477 $current_tar_size += length($$dataRef);
479 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
481 # just buffer and return
483 $WriteBuf .= $$dataRef;
486 my $done = $WriteBufSz - length($WriteBuf);
487 if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
489 die "Unable to write to output file ($!)\n";
491 while ( $done + $WriteBufSz <= length($$dataRef) ) {
492 if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
494 die "Unable to write to output file ($!)\n";
496 $done += $WriteBufSz;
498 $WriteBuf = substr($$dataRef, $done);
505 if ( $size % $tar_header_length ) {
506 my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
507 TarWrite($fh, \$data);
515 $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
516 $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
517 my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
519 my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
522 if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
524 # GNU extension for files >= 8GB: send size in big-endian binary
526 $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
527 $hdr->{size} / (65536 * 65536),
528 $hdr->{size} % (65536 * 65536));
529 } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
531 # sprintf octal only handles up to 2^32 - 1
533 $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
534 . sprintf("%08o", $hdr->{size} % (1 << 24));
536 $sizeStr = sprintf("%011o", $hdr->{size});
538 my $data = pack($tar_pack_header,
539 substr($hdr->{name}, 0, 99),
540 sprintf("%07o", $hdr->{mode}),
541 sprintf("%07o", $hdr->{uid}),
542 sprintf("%07o", $hdr->{gid}),
544 sprintf("%011o", $hdr->{mtime}),
545 "", #checksum field - space padded by pack("A8")
547 substr($hdr->{linkname}, 0, 99),
548 $hdr->{magic} || 'ustar ',
549 $hdr->{version} || ' ',
556 substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
557 TarWrite($fh, \$data);
565 # Handle long link names (symbolic links)
567 if ( length($hdr->{linkname}) > 99 ) {
569 my $data = $hdr->{linkname} . "\0";
570 $h{name} = "././\@LongLink";
572 $h{size} = length($data);
573 TarWriteHeader($fh, \%h);
574 TarWrite($fh, \$data);
575 TarWritePad($fh, length($data));
578 # Handle long file names
580 if ( length($hdr->{name}) > 99 ) {
582 my $data = $hdr->{name} . "\0";
583 $h{name} = "././\@LongLink";
585 $h{size} = length($data);
586 TarWriteHeader($fh, \%h);
587 TarWrite($fh, \$data);
588 TarWritePad($fh, length($data));
590 TarWriteHeader($fh, $hdr);
594 # seed cache of files in this increment
597 my ($host, $share, $dumpNo) = @_;
599 print STDERR curr_time(), "$host:$share #$dumpNo" if ($opts{v});
603 JOIN shares on shares.id = shareid
604 JOIN hosts on hosts.id = shares.hostid
605 WHERE hosts.name = ? and shares.name = ? and backupnum = ?
608 my $sth = $dbh->prepare($sql);
609 $sth->execute($host, $share, $dumpNo);
610 my $count = $sth->rows;
611 print STDERR " $count items, parts:" if ($opts{v});
612 while (my $row = $sth->fetchrow_arrayref) {
613 #print STDERR "+ ", $row->[0],"\n";
614 $in_backup_increment->{ $row->[0] } = $row->[1];
623 # calculate overhad for one file in tar
625 sub tar_overhead($) {
626 my $name = shift || '';
628 # header, padding of file and two null blocks at end
629 my $len = 4 * $tar_header_length;
631 # if filename is longer than 99 chars subtract blocks for
633 if ( length($name) > 99 ) {
634 $len += int( ( length($name) + $tar_header_length ) / $tar_header_length ) * $tar_header_length;
645 my($hdr, $fh, $tarPathOverride) = @_;
647 my $tarPath = $hdr->{relPath};
648 $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
650 $tarPath =~ s{//+}{/}g;
652 #print STDERR "? $tarPath\n" if ($opts{d});
653 my $size = $in_backup_increment->{$tarPath};
654 return unless (defined($size));
656 # is this file too large to fit into MaxArchiveFileSize?
658 if ( ($current_tar_size + tar_overhead($tarPath) + $size) > $max_file_size ) {
659 print STDERR "# tar file $current_tar_size + $tar_header_length + $size > $max_file_size, splitting\n" if ($opts{d});
663 #print STDERR "A $tarPath [$size] tell: $current_tar_size\n" if ($opts{d});
666 if ( defined($PathRemove)
667 && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
668 substr($tarPath, 0, length($PathRemove)) = $PathAdd;
670 $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
671 $tarPath =~ s{//+}{/}g;
672 $hdr->{name} = $tarPath;
674 if ( $hdr->{type} == BPC_FTYPE_DIR ) {
676 # Directory: just write the header
678 $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
679 TarWriteFileInfo($fh, $hdr);
681 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
683 # Regular file: write the header and file
685 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
686 if ( !defined($f) ) {
687 print(STDERR "Unable to open file $hdr->{fullPath}\n");
691 # do we need to split file?
692 if ($hdr->{size} < $max_file_size) {
693 TarWriteFileInfo($fh, $hdr);
695 while ( $f->read(\$data, $BufSize) > 0 ) {
696 TarWrite($fh, \$data);
697 $size += length($data);
700 TarWritePad($fh, $size);
704 my $full_size = $hdr->{size};
705 my $orig_name = $hdr->{name};
706 my $max_part_size = $max_file_size - tar_overhead($hdr->{name});
708 my $parts = int(($full_size + $max_part_size - 1) / $max_part_size);
709 print STDERR "# splitting $orig_name [$full_size bytes] into $parts parts\n" if ($opts{d});
710 foreach my $subpart ( 1 .. $parts ) {
712 if ($subpart < $parts) {
713 $hdr->{size} = $max_part_size;
715 $hdr->{size} = $full_size % $max_part_size;
717 $hdr->{name} = $orig_name . '/' . $subpart;
718 print STDERR "## creating part $subpart ",$hdr->{name}, " [", $hdr->{size}," bytes]\n";
720 TarWriteFileInfo($fh, $hdr);
723 for ( 1 .. int($hdr->{size} / $BufSize) ) {
724 my $r_size = $f->read(\$data, $BufSize);
725 die "expected $BufSize bytes read, got $r_size bytes!" if ($r_size != $BufSize);
726 TarWrite($fh, \$data);
727 $size += length($data);
730 my $size_left = $hdr->{size} % $BufSize;
731 my $r_size = $f->read(\$data, $size_left);
732 die "expected $size_left bytes last read, got $r_size bytes!" if ($r_size != $size_left);
734 TarWrite($fh, \$data);
735 $size += length($data);
736 TarWritePad($fh, $size);
742 $ByteCnt += $full_size;
745 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
747 # Hardlink file: either write a hardlink or the complete file
748 # depending upon whether the linked-to file will be written
751 # Start by reading the contents of the link.
753 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
754 if ( !defined($f) ) {
755 print(STDERR "Unable to open file $hdr->{fullPath}\n");
760 while ( $f->read(\$data, $BufSize) > 0 ) {
761 $hdr->{linkname} .= $data;
765 my $name = $hdr->{linkname};
767 if ( $HardLinkExtraFiles{$name} ) {
769 # Target file will be or was written, so just remember
770 # the hardlink so we can dump it later.
772 push(@HardLinks, $hdr);
776 # Have to dump the original file. Just call the top-level
777 # routine, so that we save the hassle of dealing with
778 # mangling, merging and attributes.
780 $HardLinkExtraFiles{$hdr->{linkname}} = 1;
781 archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
783 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
785 # Symbolic link: read the symbolic link contents into the header
786 # and write the header.
788 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
789 if ( !defined($f) ) {
790 print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
795 while ( $f->read(\$data, $BufSize) > 0 ) {
796 $hdr->{linkname} .= $data;
800 TarWriteFileInfo($fh, $hdr);
802 } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
803 || $hdr->{type} == BPC_FTYPE_BLOCKDEV
804 || $hdr->{type} == BPC_FTYPE_FIFO ) {
806 # Special files: for char and block special we read the
807 # major and minor numbers from a plain file.
809 if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
810 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
813 if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
814 print(STDERR "Unable to open/read char/block special file"
815 . " $hdr->{fullPath}\n");
816 $f->close if ( defined($f) );
821 if ( $data =~ /(\d+),(\d+)/ ) {
822 $hdr->{devmajor} = $1;
823 $hdr->{devminor} = $2;
827 TarWriteFileInfo($fh, $hdr);
830 print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
835 my $t_fmt = '%Y-%m-%d %H:%M:%S';
837 return strftime($t_fmt,localtime());