/[BackupPC]/trunk/bin/BackupPC_tarIncCreate
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /trunk/bin/BackupPC_tarIncCreate

Parent Directory Parent Directory | Revision Log Revision Log


Revision 261 - (hide annotations)
Mon Dec 12 21:11:17 2005 UTC (18 years, 5 months ago) by dpavlin
File size: 23494 byte(s)
 r11653@llin:  dpavlin | 2005-12-12 23:11:12 +0100
 cleanup old single archive increment if it exists

1 dpavlin 234 #!/usr/bin/perl -w
2 dpavlin 100 #============================================================= -*-perl-*-
3     #
4 dpavlin 109 # BackupPC_tarIncCreate: create a tar archive of an existing incremental dump
5     #
6 dpavlin 100 #
7     # DESCRIPTION
8     #
9 dpavlin 112 # Usage: BackupPC_tarIncCreate [options]
10 dpavlin 100 #
11     # Flags:
12     # Required options:
13     #
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.
19     #
20     # Other options:
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)
26     #
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.
31     #
32     # AUTHOR
33     # Craig Barratt <cbarratt@users.sourceforge.net>
34 dpavlin 112 # Ivan Klaric <iklaric@gmail.com>
35     # Dobrica Pavlinusic <dpavlin@rot13.org>
36 dpavlin 100 #
37     # COPYRIGHT
38     # Copyright (C) 2001-2003 Craig Barratt
39     #
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.
44     #
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.
49     #
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
53     #
54     #========================================================================
55     #
56     # Version 2.1.0, released 20 Jun 2004.
57     #
58     # See http://backuppc.sourceforge.net.
59     #
60     #========================================================================
61    
62     use strict;
63     no utf8;
64     use lib "__INSTALLDIR__/lib";
65     use File::Path;
66     use Getopt::Std;
67     use DBI;
68     use BackupPC::Lib;
69     use BackupPC::Attrib qw(:all);
70     use BackupPC::FileZIO;
71     use BackupPC::View;
72     use BackupPC::SearchLib;
73 dpavlin 112 use Time::HiRes qw/time/;
74     use POSIX qw/strftime/;
75 dpavlin 234 use File::Which;
76     use File::Path;
77 dpavlin 235 use File::Slurp;
78 dpavlin 112 use Data::Dumper; ### FIXME
79 dpavlin 100
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 dpavlin 234 %BackupPC::SearchLib::Conf = %Conf;
85 dpavlin 100 my %opts;
86 dpavlin 112 my $in_backup_increment;
87 dpavlin 100
88 dpavlin 112
89 dpavlin 252 if ( !getopts("th:n:p:r:s:b:w:vdf", \%opts) ) {
90 dpavlin 100 print STDERR <<EOF;
91 dpavlin 112 usage: $0 [options]
92 dpavlin 100 Required options:
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
98    
99     Other options:
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 dpavlin 252 -f overwrite existing parts
106 dpavlin 156 -v verbose output
107 dpavlin 234 -d debug output
108 dpavlin 100 EOF
109     exit(1);
110     }
111    
112     if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
113 dpavlin 236 die "$0: bad host name '$opts{h}'\n";
114 dpavlin 100 }
115     my $Host = $opts{h};
116    
117     if ( $opts{n} !~ /^(-?\d+)$/ ) {
118 dpavlin 236 die "$0: bad dump number '$opts{n}'\n";
119 dpavlin 100 }
120     my $Num = $opts{n};
121    
122 dpavlin 234 my $bin;
123     foreach my $c (qw/gzip md5sum tee/) {
124     $bin->{$c} = which($c) || die "$0 needs $c, install it\n";
125     }
126    
127 dpavlin 100 my @Backups = $bpc->BackupInfoRead($Host);
128     my $FileCnt = 0;
129     my $ByteCnt = 0;
130     my $DirCnt = 0;
131     my $SpecialCnt = 0;
132     my $ErrorCnt = 0;
133 dpavlin 234 my $current_tar_size = 0;
134 dpavlin 236 my $total_increment_size = 0;
135 dpavlin 100
136     my $i;
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 );
140     }
141     if ( $i >= @Backups ) {
142 dpavlin 236 die "$0: bad backup number $Num for host $Host\n";
143 dpavlin 100 }
144    
145     my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
146     my $PathAdd = $1 if ( $opts{p} =~ /(.+)/ );
147     if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ && $opts{s} ne "*" ) {
148 dpavlin 236 die "$0: bad share name '$opts{s}'\n";
149 dpavlin 100 }
150     our $ShareName = $opts{s};
151     our $view = BackupPC::View->new($bpc, $Host, \@Backups);
152    
153 dpavlin 235 # database
154    
155     my $dsn = $Conf{SearchDSN};
156     my $db_user = $Conf{SearchUser} || '';
157    
158     my $dbh = DBI->connect($dsn, $db_user, "", { RaiseError => 1, AutoCommit => 0} );
159    
160     my $sth_inc_size = $dbh->prepare(qq{
161     update backups set
162     inc_size = ?,
163     parts = ?,
164     inc_deleted = false
165 dpavlin 251 where id = ?
166     });
167 dpavlin 235 my $sth_backup_parts = $dbh->prepare(qq{
168     insert into backup_parts (
169     backup_id,
170     part_nr,
171     tar_size,
172     size,
173     md5,
174     items
175     ) values (?,?,?,?,?,?)
176     });
177    
178 dpavlin 100 #
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.
181     # See www.cpan.org.
182     #
183     # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
184     # Copyright 1998 Stephen Zander. All rights reserved.
185     #
186     my $tar_pack_header
187     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
188     my $tar_header_length = 512;
189    
190     my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
191     my $WriteBuf = "";
192     my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
193    
194     my(%UidCache, %GidCache);
195     my(%HardLinkExtraFiles, @HardLinks);
196    
197     #
198     # Write out all the requested files/directories
199     #
200 dpavlin 112
201 dpavlin 234 my $max_file_size = $Conf{'MaxArchiveFileSize'} || die "problem with MaxArchiveFileSize parametar";
202    
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);
205    
206     my $tar_file = BackupPC::SearchLib::getGzipName($Host, $ShareName, $Num) || die "can't getGzipName($Host, $ShareName, $Num)";
207    
208 dpavlin 251 my $tar_path_final = $tar_dir . '/' . $tar_file;
209     my $tar_path = $tar_path_final . '.tmp';
210    
211 dpavlin 234 $tar_path =~ s#//#/#g;
212    
213 dpavlin 235 my $sth = $dbh->prepare(qq{
214     SELECT
215     backups.id
216     FROM backups
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 = ?
220     });
221     $sth->execute($Host, $ShareName, $Num);
222     my ($backup_id) = $sth->fetchrow_array;
223     $sth->finish;
224 dpavlin 234
225 dpavlin 257
226     # delete exising backup_parts
227     my $sth_delete_backup_parts = $dbh->prepare(qq{
228     delete from backup_parts
229     where backup_id = ?
230     });
231     $sth_delete_backup_parts->execute($backup_id);
232    
233    
234 dpavlin 235 print STDERR "backup_id: $backup_id working dir: $tar_dir, max uncompressed size $max_file_size bytes, tar $tar_file\n" if ($opts{d});
235    
236 dpavlin 252 if (-e $tar_path_final) {
237     if ($opts{f}) {
238     rmtree $tar_path_final || die "can't remove $tar_path_final: $!";
239     } else {
240     die "$tar_path_final allready exists\n";
241     }
242     }
243 dpavlin 235
244 dpavlin 234 my $fh;
245     my $part = 0;
246     my $no_files = 0;
247 dpavlin 235 my $items_in_part = 0;
248 dpavlin 234
249     sub new_tar_part {
250 dpavlin 236 my $arg = {@_};
251    
252 dpavlin 234 if ($fh) {
253     return if ($current_tar_size == 0);
254    
255 dpavlin 254 print STDERR " $part";
256 dpavlin 234
257 dpavlin 236 #
258     # Finish with two null 512 byte headers,
259     # and then round out a full block.
260     #
261 dpavlin 234 my $data = "\0" x ($tar_header_length * 2);
262     TarWrite($fh, \$data);
263     TarWrite($fh, undef);
264    
265     close($fh) || die "can't close archive part $part: $!";
266 dpavlin 235
267     my $file = $tar_path . '/' . $part;
268    
269     my $md5 = read_file( $file . '.md5' ) || die "can't read md5sum file ${file}.md5";
270     $md5 =~ s/\s.*$//;
271    
272     my $size = (stat( $file . '.tar.gz' ))[7] || die "can't stat ${file}.tar.gz";
273    
274     $sth_backup_parts->execute(
275     $backup_id,
276     $part,
277     $current_tar_size,
278     $size,
279     $md5,
280     $items_in_part,
281     );
282    
283 dpavlin 253 $total_increment_size += $size;
284 dpavlin 236
285     if ($arg->{close}) {
286 dpavlin 251
287 dpavlin 252 sub move($$) {
288     my ($from,$to) = @_;
289     print STDERR "# rename $from -> $to\n" if ($opts{d});
290     rename $from, $to || die "can't move $from -> $to: $!\n";
291     }
292    
293 dpavlin 251 if ($part == 1) {
294 dpavlin 254 print STDERR " single" if ($opts{v});
295 dpavlin 252 move("${tar_path}/1.tar.gz", "${tar_path_final}.tar.gz");
296     move("${tar_path}/1.md5", "${tar_path_final}.md5");
297     rmtree $tar_path or die "can't remove temporary dir $tar_path: $!";
298 dpavlin 251 } else {
299 dpavlin 254 print STDERR " [last]" if ($opts{v});
300 dpavlin 252 move("${tar_path}", "${tar_path_final}");
301 dpavlin 261
302     # if this archive was single part, remove it
303     foreach my $suffix (qw/.tar.gz .md5/) {
304     my $path = $tar_path_final . $suffix;
305     unlink $path if (-e $path);
306     }
307 dpavlin 251 }
308    
309 dpavlin 236 $sth_inc_size->execute(
310     $total_increment_size,
311     $part,
312     $backup_id
313     );
314 dpavlin 251
315     print STDERR ", $total_increment_size bytes\n" if ($opts{v});
316    
317 dpavlin 236 return;
318     }
319    
320 dpavlin 234 }
321    
322     $part++;
323    
324     # if this is first part, create directory
325    
326     if ($part == 1) {
327 dpavlin 253 if (-e $tar_path) {
328 dpavlin 234 print STDERR "# deleting existing $tar_path\n" if ($opts{d});
329     rmtree($tar_path);
330     }
331     mkdir($tar_path) || die "can't create directory $tar_path: $!";
332 dpavlin 236
333     sub abort_cleanup {
334     print STDERR "ABORTED: cleanup temp dir";
335     rmtree($tar_path);
336     $dbh->rollback;
337     exit 1;
338     }
339    
340     $SIG{'INT'} = \&abort_cleanup;
341     $SIG{'QUIT'} = \&abort_cleanup;
342     $SIG{'__DIE__'} = \&abort_cleanup;
343    
344 dpavlin 234 }
345    
346     my $file = $tar_path . '/' . $part;
347    
348     #
349     # create comprex pipe which will pass output through gzip
350     # for compression, create file on disk using tee
351     # and pipe same output to md5sum to create checksum
352     #
353    
354     my $cmd = '| ' . $bin->{'gzip'} . ' ' . $Conf{GzipLevel} . ' ' .
355     '| ' . $bin->{'tee'} . ' ' . $file . '.tar.gz' . ' ' .
356     '| ' . $bin->{'md5sum'} . ' - > ' . $file . '.md5';
357    
358     print STDERR "## $cmd\n" if ($opts{d});
359    
360     open($fh, $cmd) or die "can't open $cmd: $!";
361     binmode($fh);
362 dpavlin 235
363 dpavlin 234 $current_tar_size = 0;
364 dpavlin 235 $items_in_part = 0;
365 dpavlin 234 }
366    
367     new_tar_part();
368    
369 dpavlin 112 if (seedCache($Host, $ShareName, $Num)) {
370     archiveWrite($fh, '/');
371     archiveWriteHardLinks($fh);
372 dpavlin 252 new_tar_part( close => 1 );
373 dpavlin 100 } else {
374 dpavlin 170 print STDERR "NOTE: no files found for $Host:$ShareName, increment $Num\n" if ($opts{v});
375 dpavlin 252 # remove temporary files if there are no files
376 dpavlin 234 rmtree($tar_path);
377     }
378    
379 dpavlin 100 #
380     # print out totals if requested
381     #
382     if ( $opts{t} ) {
383     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
384     " $SpecialCnt specials, $ErrorCnt errors\n";
385     }
386     if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
387     #
388     # Got errors, with no files or directories; exit with non-zero
389     # status
390     #
391 dpavlin 236 die "got errors or no files\n";
392 dpavlin 100 }
393 dpavlin 234
394 dpavlin 235 $sth_inc_size->finish;
395     $sth_backup_parts->finish;
396    
397     $dbh->commit || die "can't commit changes to database";
398     $dbh->disconnect();
399    
400 dpavlin 236 exit;
401 dpavlin 100
402     ###########################################################################
403     # Subroutines
404     ###########################################################################
405    
406     sub archiveWrite
407     {
408     my($fh, $dir, $tarPathOverride) = @_;
409    
410     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
411     print(STDERR "$0: bad directory '$dir'\n");
412     $ErrorCnt++;
413     return;
414     }
415     $dir = "/" if ( $dir eq "." );
416     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
417    
418     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
419     $fh, $tarPathOverride) < 0 ) {
420     print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
421     $ErrorCnt++;
422     return;
423     }
424     }
425    
426     #
427     # Write out any hardlinks (if any)
428     #
429     sub archiveWriteHardLinks
430     {
431     my $fh = @_;
432     foreach my $hdr ( @HardLinks ) {
433     $hdr->{size} = 0;
434     if ( defined($PathRemove)
435     && substr($hdr->{linkname}, 0, length($PathRemove)+1)
436     eq ".$PathRemove" ) {
437     substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
438     }
439     TarWriteFileInfo($fh, $hdr);
440     }
441     @HardLinks = ();
442     %HardLinkExtraFiles = ();
443     }
444    
445     sub UidLookup
446     {
447     my($uid) = @_;
448    
449     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
450     return $UidCache{$uid};
451     }
452    
453     sub GidLookup
454     {
455     my($gid) = @_;
456    
457     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
458     return $GidCache{$gid};
459     }
460    
461     sub TarWrite
462     {
463     my($fh, $dataRef) = @_;
464    
465 dpavlin 234
466 dpavlin 100 if ( !defined($dataRef) ) {
467     #
468     # do flush by padding to a full $WriteBufSz
469     #
470     my $data = "\0" x ($WriteBufSz - length($WriteBuf));
471     $dataRef = \$data;
472     }
473 dpavlin 234
474     # poor man's tell :-)
475     $current_tar_size += length($$dataRef);
476    
477 dpavlin 100 if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
478     #
479     # just buffer and return
480     #
481     $WriteBuf .= $$dataRef;
482     return;
483     }
484     my $done = $WriteBufSz - length($WriteBuf);
485     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
486     != $WriteBufSz ) {
487 dpavlin 236 die "Unable to write to output file ($!)\n";
488 dpavlin 100 }
489     while ( $done + $WriteBufSz <= length($$dataRef) ) {
490     if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
491     != $WriteBufSz ) {
492 dpavlin 236 die "Unable to write to output file ($!)\n";
493 dpavlin 100 }
494     $done += $WriteBufSz;
495     }
496     $WriteBuf = substr($$dataRef, $done);
497     }
498    
499     sub TarWritePad
500     {
501     my($fh, $size) = @_;
502    
503     if ( $size % $tar_header_length ) {
504     my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
505     TarWrite($fh, \$data);
506     }
507     }
508    
509     sub TarWriteHeader
510     {
511     my($fh, $hdr) = @_;
512    
513     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
514     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
515     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
516     : "";
517     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
518     : "";
519     my $sizeStr;
520     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
521     #
522     # GNU extension for files >= 8GB: send size in big-endian binary
523     #
524     $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
525     $hdr->{size} / (65536 * 65536),
526     $hdr->{size} % (65536 * 65536));
527     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
528     #
529     # sprintf octal only handles up to 2^32 - 1
530     #
531     $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
532     . sprintf("%08o", $hdr->{size} % (1 << 24));
533     } else {
534     $sizeStr = sprintf("%011o", $hdr->{size});
535     }
536     my $data = pack($tar_pack_header,
537     substr($hdr->{name}, 0, 99),
538     sprintf("%07o", $hdr->{mode}),
539     sprintf("%07o", $hdr->{uid}),
540     sprintf("%07o", $hdr->{gid}),
541     $sizeStr,
542     sprintf("%011o", $hdr->{mtime}),
543     "", #checksum field - space padded by pack("A8")
544     $hdr->{type},
545     substr($hdr->{linkname}, 0, 99),
546     $hdr->{magic} || 'ustar ',
547     $hdr->{version} || ' ',
548     $hdr->{uname},
549     $hdr->{gname},
550     $devmajor,
551     $devminor,
552     "" # prefix is empty
553     );
554     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
555     TarWrite($fh, \$data);
556     }
557    
558     sub TarWriteFileInfo
559     {
560     my($fh, $hdr) = @_;
561    
562     #
563     # Handle long link names (symbolic links)
564     #
565     if ( length($hdr->{linkname}) > 99 ) {
566     my %h;
567     my $data = $hdr->{linkname} . "\0";
568     $h{name} = "././\@LongLink";
569     $h{type} = "K";
570     $h{size} = length($data);
571     TarWriteHeader($fh, \%h);
572     TarWrite($fh, \$data);
573     TarWritePad($fh, length($data));
574     }
575     #
576     # Handle long file names
577     #
578     if ( length($hdr->{name}) > 99 ) {
579     my %h;
580     my $data = $hdr->{name} . "\0";
581     $h{name} = "././\@LongLink";
582     $h{type} = "L";
583     $h{size} = length($data);
584     TarWriteHeader($fh, \%h);
585     TarWrite($fh, \$data);
586     TarWritePad($fh, length($data));
587     }
588     TarWriteHeader($fh, $hdr);
589     }
590    
591     #
592 dpavlin 112 # seed cache of files in this increment
593 dpavlin 100 #
594 dpavlin 112 sub seedCache($$$) {
595     my ($host, $share, $dumpNo) = @_;
596    
597 dpavlin 251 print STDERR curr_time(), "$host:$share #$dumpNo" if ($opts{v});
598 dpavlin 112 my $sql = q{
599 dpavlin 234 SELECT path,size
600 dpavlin 112 FROM files
601     JOIN shares on shares.id = shareid
602     JOIN hosts on hosts.id = shares.hostid
603     WHERE hosts.name = ? and shares.name = ? and backupnum = ?
604     };
605 dpavlin 100
606 dpavlin 112 my $sth = $dbh->prepare($sql);
607     $sth->execute($host, $share, $dumpNo);
608     my $count = $sth->rows;
609 dpavlin 251 print STDERR " $count items, parts:" if ($opts{v});
610 dpavlin 112 while (my $row = $sth->fetchrow_arrayref) {
611 dpavlin 156 #print STDERR "+ ", $row->[0],"\n";
612 dpavlin 234 $in_backup_increment->{ $row->[0] } = $row->[1];
613 dpavlin 100 }
614 dpavlin 112
615     $sth->finish();
616 dpavlin 100
617 dpavlin 112 return $count;
618 dpavlin 100 }
619    
620 dpavlin 234 #
621     # calculate overhad for one file in tar
622     #
623     sub tar_overhead($) {
624     my $name = shift || '';
625    
626     # header, padding of file and two null blocks at end
627     my $len = 4 * $tar_header_length;
628    
629     # if filename is longer than 99 chars subtract blocks for
630     # long filename
631     if ( length($name) > 99 ) {
632     $len += int( ( length($name) + $tar_header_length ) / $tar_header_length ) * $tar_header_length;
633     }
634    
635     return $len;
636     }
637    
638 dpavlin 100 my $Attr;
639     my $AttrDir;
640    
641     sub TarWriteFile
642     {
643     my($hdr, $fh, $tarPathOverride) = @_;
644    
645     my $tarPath = $hdr->{relPath};
646     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
647    
648     $tarPath =~ s{//+}{/}g;
649 dpavlin 112
650 dpavlin 234 #print STDERR "? $tarPath\n" if ($opts{d});
651     my $size = $in_backup_increment->{$tarPath};
652     return unless (defined($size));
653 dpavlin 112
654 dpavlin 234 # is this file too large to fit into MaxArchiveFileSize?
655    
656     if ( ($current_tar_size + tar_overhead($tarPath) + $size) > $max_file_size ) {
657 dpavlin 251 print STDERR "# tar file $current_tar_size + $tar_header_length + $size > $max_file_size, splitting\n" if ($opts{d});
658 dpavlin 234 new_tar_part();
659     }
660    
661 dpavlin 235 #print STDERR "A $tarPath [$size] tell: $current_tar_size\n" if ($opts{d});
662     $items_in_part++;
663 dpavlin 234
664 dpavlin 100 if ( defined($PathRemove)
665     && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
666     substr($tarPath, 0, length($PathRemove)) = $PathAdd;
667     }
668     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
669     $tarPath =~ s{//+}{/}g;
670     $hdr->{name} = $tarPath;
671    
672     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
673     #
674     # Directory: just write the header
675     #
676     $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
677 dpavlin 112 TarWriteFileInfo($fh, $hdr);
678     $DirCnt++;
679 dpavlin 100 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
680     #
681     # Regular file: write the header and file
682     #
683     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
684     if ( !defined($f) ) {
685     print(STDERR "Unable to open file $hdr->{fullPath}\n");
686     $ErrorCnt++;
687     return;
688     }
689 dpavlin 234 # do we need to split file?
690     if ($hdr->{size} < $max_file_size) {
691     TarWriteFileInfo($fh, $hdr);
692     my($data, $size);
693     while ( $f->read(\$data, $BufSize) > 0 ) {
694     TarWrite($fh, \$data);
695     $size += length($data);
696     }
697     $f->close;
698     TarWritePad($fh, $size);
699 dpavlin 100 $FileCnt++;
700     $ByteCnt += $size;
701 dpavlin 234 } else {
702     my $full_size = $hdr->{size};
703     my $orig_name = $hdr->{name};
704     my $max_part_size = $max_file_size - tar_overhead($hdr->{name});
705    
706     my $parts = int(($full_size + $max_part_size - 1) / $max_part_size);
707     print STDERR "# splitting $orig_name [$full_size bytes] into $parts parts\n" if ($opts{d});
708     foreach my $subpart ( 1 .. $parts ) {
709     new_tar_part();
710     if ($subpart < $parts) {
711     $hdr->{size} = $max_part_size;
712     } else {
713     $hdr->{size} = $full_size % $max_part_size;
714     }
715     $hdr->{name} = $orig_name . '/' . $subpart;
716     print STDERR "## creating part $subpart ",$hdr->{name}, " [", $hdr->{size}," bytes]\n";
717    
718     TarWriteFileInfo($fh, $hdr);
719     my($data, $size);
720     if (0) {
721     for ( 1 .. int($hdr->{size} / $BufSize) ) {
722     my $r_size = $f->read(\$data, $BufSize);
723     die "expected $BufSize bytes read, got $r_size bytes!" if ($r_size != $BufSize);
724     TarWrite($fh, \$data);
725     $size += length($data);
726     }
727     }
728     my $size_left = $hdr->{size} % $BufSize;
729     my $r_size = $f->read(\$data, $size_left);
730     die "expected $size_left bytes last read, got $r_size bytes!" if ($r_size != $size_left);
731    
732     TarWrite($fh, \$data);
733     $size += length($data);
734     TarWritePad($fh, $size);
735 dpavlin 235
736     $items_in_part++;
737 dpavlin 234 }
738     $f->close;
739     $FileCnt++;
740     $ByteCnt += $full_size;
741     new_tar_part();
742     }
743 dpavlin 100 } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
744     #
745     # Hardlink file: either write a hardlink or the complete file
746 dpavlin 234 # depending upon whether the linked-to file will be written
747     # to the archive.
748 dpavlin 100 #
749 dpavlin 234 # Start by reading the contents of the link.
750     #
751 dpavlin 100 my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
752     if ( !defined($f) ) {
753     print(STDERR "Unable to open file $hdr->{fullPath}\n");
754     $ErrorCnt++;
755     return;
756     }
757     my $data;
758     while ( $f->read(\$data, $BufSize) > 0 ) {
759     $hdr->{linkname} .= $data;
760     }
761 dpavlin 234 $f->close;
762     my $done = 0;
763     my $name = $hdr->{linkname};
764     $name =~ s{^\./}{/};
765     if ( $HardLinkExtraFiles{$name} ) {
766     #
767     # Target file will be or was written, so just remember
768     # the hardlink so we can dump it later.
769     #
770     push(@HardLinks, $hdr);
771     $SpecialCnt++;
772     } else {
773     #
774     # Have to dump the original file. Just call the top-level
775     # routine, so that we save the hassle of dealing with
776     # mangling, merging and attributes.
777     #
778     $HardLinkExtraFiles{$hdr->{linkname}} = 1;
779     archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
780     }
781 dpavlin 100 } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
782     #
783     # Symbolic link: read the symbolic link contents into the header
784     # and write the header.
785     #
786     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
787     if ( !defined($f) ) {
788     print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
789     $ErrorCnt++;
790     return;
791     }
792     my $data;
793     while ( $f->read(\$data, $BufSize) > 0 ) {
794     $hdr->{linkname} .= $data;
795     }
796     $f->close;
797     $hdr->{size} = 0;
798     TarWriteFileInfo($fh, $hdr);
799     $SpecialCnt++;
800     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
801     || $hdr->{type} == BPC_FTYPE_BLOCKDEV
802     || $hdr->{type} == BPC_FTYPE_FIFO ) {
803     #
804     # Special files: for char and block special we read the
805     # major and minor numbers from a plain file.
806     #
807     if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
808     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
809     $hdr->{compress});
810     my $data;
811     if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
812     print(STDERR "Unable to open/read char/block special file"
813     . " $hdr->{fullPath}\n");
814     $f->close if ( defined($f) );
815     $ErrorCnt++;
816     return;
817     }
818     $f->close;
819     if ( $data =~ /(\d+),(\d+)/ ) {
820     $hdr->{devmajor} = $1;
821     $hdr->{devminor} = $2;
822     }
823     }
824     $hdr->{size} = 0;
825     TarWriteFileInfo($fh, $hdr);
826     $SpecialCnt++;
827     } else {
828     print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
829     $ErrorCnt++;
830     }
831     }
832 dpavlin 112
833     my $t_fmt = '%Y-%m-%d %H:%M:%S';
834     sub curr_time {
835     return strftime($t_fmt,localtime());
836     }

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26