/[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 169 - (hide annotations)
Mon Oct 10 14:12:33 2005 UTC (18 years, 7 months ago) by dpavlin
File size: 16776 byte(s)
hush NOTE output

1 dpavlin 100 #!/usr/bin/perl
2     #============================================================= -*-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     use Data::Dumper; ### FIXME
76 dpavlin 100
77     die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
78     my $TopDir = $bpc->TopDir();
79     my $BinDir = $bpc->BinDir();
80     my %Conf = $bpc->Conf();
81     my %opts;
82 dpavlin 112 my $in_backup_increment;
83 dpavlin 100
84 dpavlin 112
85 dpavlin 156 if ( !getopts("th:n:p:r:s:b:w:v", \%opts) ) {
86 dpavlin 100 print STDERR <<EOF;
87 dpavlin 112 usage: $0 [options]
88 dpavlin 100 Required options:
89     -h host host from which the tar archive is created
90     -n dumpNum dump number from which the tar archive is created
91     A negative number means relative to the end (eg -1
92     means the most recent dump, -2 2nd most recent etc).
93     -s shareName share name from which the tar archive is created
94    
95     Other options:
96     -t print summary totals
97     -r pathRemove path prefix that will be replaced with pathAdd
98     -p pathAdd new path prefix
99     -b BLOCKS BLOCKS x 512 bytes per record (default 20; same as tar)
100     -w writeBufSz write buffer size (default 1048576 = 1MB)
101 dpavlin 156 -v verbose output
102 dpavlin 100 EOF
103     exit(1);
104     }
105    
106     if ( $opts{h} !~ /^([\w\.\s-]+)$/ ) {
107     print(STDERR "$0: bad host name '$opts{h}'\n");
108     exit(1);
109     }
110     my $Host = $opts{h};
111    
112     if ( $opts{n} !~ /^(-?\d+)$/ ) {
113     print(STDERR "$0: bad dump number '$opts{n}'\n");
114     exit(1);
115     }
116     my $Num = $opts{n};
117    
118     my @Backups = $bpc->BackupInfoRead($Host);
119     my $FileCnt = 0;
120     my $ByteCnt = 0;
121     my $DirCnt = 0;
122     my $SpecialCnt = 0;
123     my $ErrorCnt = 0;
124    
125     my $i;
126     $Num = $Backups[@Backups + $Num]{num} if ( -@Backups <= $Num && $Num < 0 );
127     for ( $i = 0 ; $i < @Backups ; $i++ ) {
128     last if ( $Backups[$i]{num} == $Num );
129     }
130     if ( $i >= @Backups ) {
131     print(STDERR "$0: bad backup number $Num for host $Host\n");
132     exit(1);
133     }
134    
135     my $PathRemove = $1 if ( $opts{r} =~ /(.+)/ );
136     my $PathAdd = $1 if ( $opts{p} =~ /(.+)/ );
137     if ( $opts{s} !~ /^([\w\s\.\/\$-]+)$/ && $opts{s} ne "*" ) {
138     print(STDERR "$0: bad share name '$opts{s}'\n");
139     exit(1);
140     }
141     our $ShareName = $opts{s};
142     our $view = BackupPC::View->new($bpc, $Host, \@Backups);
143    
144     #
145     # This constant and the line of code below that uses it are borrowed
146     # from Archive::Tar. Thanks to Calle Dybedahl and Stephen Zander.
147     # See www.cpan.org.
148     #
149     # Archive::Tar is Copyright 1997 Calle Dybedahl. All rights reserved.
150     # Copyright 1998 Stephen Zander. All rights reserved.
151     #
152     my $tar_pack_header
153     = 'a100 a8 a8 a8 a12 a12 A8 a1 a100 a6 a2 a32 a32 a8 a8 a155 x12';
154     my $tar_header_length = 512;
155    
156     my $BufSize = $opts{w} || 1048576; # 1MB or 2^20
157     my $WriteBuf = "";
158     my $WriteBufSz = ($opts{b} || 20) * $tar_header_length;
159    
160     my(%UidCache, %GidCache);
161     my(%HardLinkExtraFiles, @HardLinks);
162    
163     #
164     # Write out all the requested files/directories
165     #
166     binmode(STDOUT);
167     my $fh = *STDOUT;
168 dpavlin 112
169     if (seedCache($Host, $ShareName, $Num)) {
170     archiveWrite($fh, '/');
171     archiveWriteHardLinks($fh);
172 dpavlin 100 } else {
173 dpavlin 169 print STDERR "NOTE: no files found for $Host:$ShareName, increment $Num\n" if ($opt{v});
174 dpavlin 100 }
175    
176     #
177     # Finish with two null 512 byte headers, and then round out a full
178     # block.
179     #
180     my $data = "\0" x ($tar_header_length * 2);
181     TarWrite($fh, \$data);
182     TarWrite($fh, undef);
183    
184     #
185     # print out totals if requested
186     #
187     if ( $opts{t} ) {
188     print STDERR "Done: $FileCnt files, $ByteCnt bytes, $DirCnt dirs,",
189     " $SpecialCnt specials, $ErrorCnt errors\n";
190     }
191     if ( $ErrorCnt && !$FileCnt && !$DirCnt ) {
192     #
193     # Got errors, with no files or directories; exit with non-zero
194     # status
195     #
196     exit(1);
197     }
198     exit(0);
199    
200     ###########################################################################
201     # Subroutines
202     ###########################################################################
203    
204     sub archiveWrite
205     {
206     my($fh, $dir, $tarPathOverride) = @_;
207    
208     if ( $dir =~ m{(^|/)\.\.(/|$)} ) {
209     print(STDERR "$0: bad directory '$dir'\n");
210     $ErrorCnt++;
211     return;
212     }
213     $dir = "/" if ( $dir eq "." );
214     #print(STDERR "calling find with $Num, $ShareName, $dir\n");
215    
216     if ( $view->find($Num, $ShareName, $dir, 0, \&TarWriteFile,
217     $fh, $tarPathOverride) < 0 ) {
218     print(STDERR "$0: bad share or directory '$ShareName/$dir'\n");
219     $ErrorCnt++;
220     return;
221     }
222     }
223    
224     #
225     # Write out any hardlinks (if any)
226     #
227     sub archiveWriteHardLinks
228     {
229     my $fh = @_;
230     foreach my $hdr ( @HardLinks ) {
231     $hdr->{size} = 0;
232     if ( defined($PathRemove)
233     && substr($hdr->{linkname}, 0, length($PathRemove)+1)
234     eq ".$PathRemove" ) {
235     substr($hdr->{linkname}, 0, length($PathRemove)+1) = ".$PathAdd";
236     }
237     TarWriteFileInfo($fh, $hdr);
238     }
239     @HardLinks = ();
240     %HardLinkExtraFiles = ();
241     }
242    
243     sub UidLookup
244     {
245     my($uid) = @_;
246    
247     $UidCache{$uid} = (getpwuid($uid))[0] if ( !exists($UidCache{$uid}) );
248     return $UidCache{$uid};
249     }
250    
251     sub GidLookup
252     {
253     my($gid) = @_;
254    
255     $GidCache{$gid} = (getgrgid($gid))[0] if ( !exists($GidCache{$gid}) );
256     return $GidCache{$gid};
257     }
258    
259     sub TarWrite
260     {
261     my($fh, $dataRef) = @_;
262    
263     if ( !defined($dataRef) ) {
264     #
265     # do flush by padding to a full $WriteBufSz
266     #
267     my $data = "\0" x ($WriteBufSz - length($WriteBuf));
268     $dataRef = \$data;
269     }
270     if ( length($WriteBuf) + length($$dataRef) < $WriteBufSz ) {
271     #
272     # just buffer and return
273     #
274     $WriteBuf .= $$dataRef;
275     return;
276     }
277     my $done = $WriteBufSz - length($WriteBuf);
278     if ( syswrite($fh, $WriteBuf . substr($$dataRef, 0, $done))
279     != $WriteBufSz ) {
280     print(STDERR "Unable to write to output file ($!)\n");
281     exit(1);
282     }
283     while ( $done + $WriteBufSz <= length($$dataRef) ) {
284     if ( syswrite($fh, substr($$dataRef, $done, $WriteBufSz))
285     != $WriteBufSz ) {
286     print(STDERR "Unable to write to output file ($!)\n");
287     exit(1);
288     }
289     $done += $WriteBufSz;
290     }
291     $WriteBuf = substr($$dataRef, $done);
292     }
293    
294     sub TarWritePad
295     {
296     my($fh, $size) = @_;
297    
298     if ( $size % $tar_header_length ) {
299     my $data = "\0" x ($tar_header_length - ($size % $tar_header_length));
300     TarWrite($fh, \$data);
301     }
302     }
303    
304     sub TarWriteHeader
305     {
306     my($fh, $hdr) = @_;
307    
308     $hdr->{uname} = UidLookup($hdr->{uid}) if ( !defined($hdr->{uname}) );
309     $hdr->{gname} = GidLookup($hdr->{gid}) if ( !defined($hdr->{gname}) );
310     my $devmajor = defined($hdr->{devmajor}) ? sprintf("%07o", $hdr->{devmajor})
311     : "";
312     my $devminor = defined($hdr->{devminor}) ? sprintf("%07o", $hdr->{devminor})
313     : "";
314     my $sizeStr;
315     if ( $hdr->{size} >= 2 * 65536 * 65536 ) {
316     #
317     # GNU extension for files >= 8GB: send size in big-endian binary
318     #
319     $sizeStr = pack("c4 N N", 0x80, 0, 0, 0,
320     $hdr->{size} / (65536 * 65536),
321     $hdr->{size} % (65536 * 65536));
322     } elsif ( $hdr->{size} >= 1 * 65536 * 65536 ) {
323     #
324     # sprintf octal only handles up to 2^32 - 1
325     #
326     $sizeStr = sprintf("%03o", $hdr->{size} / (1 << 24))
327     . sprintf("%08o", $hdr->{size} % (1 << 24));
328     } else {
329     $sizeStr = sprintf("%011o", $hdr->{size});
330     }
331     my $data = pack($tar_pack_header,
332     substr($hdr->{name}, 0, 99),
333     sprintf("%07o", $hdr->{mode}),
334     sprintf("%07o", $hdr->{uid}),
335     sprintf("%07o", $hdr->{gid}),
336     $sizeStr,
337     sprintf("%011o", $hdr->{mtime}),
338     "", #checksum field - space padded by pack("A8")
339     $hdr->{type},
340     substr($hdr->{linkname}, 0, 99),
341     $hdr->{magic} || 'ustar ',
342     $hdr->{version} || ' ',
343     $hdr->{uname},
344     $hdr->{gname},
345     $devmajor,
346     $devminor,
347     "" # prefix is empty
348     );
349     substr($data, 148, 7) = sprintf("%06o\0", unpack("%16C*",$data));
350     TarWrite($fh, \$data);
351     }
352    
353     sub TarWriteFileInfo
354     {
355     my($fh, $hdr) = @_;
356    
357     #
358     # Handle long link names (symbolic links)
359     #
360     if ( length($hdr->{linkname}) > 99 ) {
361     my %h;
362     my $data = $hdr->{linkname} . "\0";
363     $h{name} = "././\@LongLink";
364     $h{type} = "K";
365     $h{size} = length($data);
366     TarWriteHeader($fh, \%h);
367     TarWrite($fh, \$data);
368     TarWritePad($fh, length($data));
369     }
370     #
371     # Handle long file names
372     #
373     if ( length($hdr->{name}) > 99 ) {
374     my %h;
375     my $data = $hdr->{name} . "\0";
376     $h{name} = "././\@LongLink";
377     $h{type} = "L";
378     $h{size} = length($data);
379     TarWriteHeader($fh, \%h);
380     TarWrite($fh, \$data);
381     TarWritePad($fh, length($data));
382     }
383     TarWriteHeader($fh, $hdr);
384     }
385    
386     #
387 dpavlin 112 # seed cache of files in this increment
388 dpavlin 100 #
389 dpavlin 112 sub seedCache($$$) {
390     my ($host, $share, $dumpNo) = @_;
391    
392 dpavlin 100 my $dsn = $Conf{SearchDSN};
393     my $db_user = $Conf{SearchUser} || '';
394    
395 dpavlin 156 print STDERR curr_time(), "getting files for $host:$share increment $dumpNo..." if ($opts{v});
396 dpavlin 112 my $sql = q{
397     SELECT path
398     FROM files
399     JOIN shares on shares.id = shareid
400     JOIN hosts on hosts.id = shares.hostid
401     WHERE hosts.name = ? and shares.name = ? and backupnum = ?
402     };
403 dpavlin 100
404 dpavlin 112 my $dbh = DBI->connect($dsn, $db_user, "", { RaiseError => 1, AutoCommit => 1} );
405     my $sth = $dbh->prepare($sql);
406     $sth->execute($host, $share, $dumpNo);
407     my $count = $sth->rows;
408 dpavlin 156 print STDERR " found $count items\n" if ($opts{v});
409 dpavlin 112 while (my $row = $sth->fetchrow_arrayref) {
410 dpavlin 156 #print STDERR "+ ", $row->[0],"\n";
411 dpavlin 112 $in_backup_increment->{ $row->[0] }++;
412 dpavlin 100 }
413 dpavlin 112
414     $sth->finish();
415     $dbh->disconnect();
416 dpavlin 100
417 dpavlin 112 return $count;
418 dpavlin 100 }
419    
420     my $Attr;
421     my $AttrDir;
422    
423     sub TarWriteFile
424     {
425     my($hdr, $fh, $tarPathOverride) = @_;
426    
427     my $tarPath = $hdr->{relPath};
428     $tarPath = $tarPathOverride if ( defined($tarPathOverride) );
429    
430     $tarPath =~ s{//+}{/}g;
431 dpavlin 112
432     #print STDERR "? $tarPath\n";
433     return unless ($in_backup_increment->{$tarPath});
434 dpavlin 156 #print STDERR "A $tarPath\n";
435 dpavlin 112
436 dpavlin 100 if ( defined($PathRemove)
437     && substr($tarPath, 0, length($PathRemove)) eq $PathRemove ) {
438     substr($tarPath, 0, length($PathRemove)) = $PathAdd;
439     }
440     $tarPath = "./" . $tarPath if ( $tarPath !~ /^\.\// );
441     $tarPath =~ s{//+}{/}g;
442     $hdr->{name} = $tarPath;
443    
444     if ( $hdr->{type} == BPC_FTYPE_DIR ) {
445     #
446     # Directory: just write the header
447     #
448    
449    
450     $hdr->{name} .= "/" if ( $hdr->{name} !~ m{/$} );
451 dpavlin 112 TarWriteFileInfo($fh, $hdr);
452     $DirCnt++;
453 dpavlin 100 } elsif ( $hdr->{type} == BPC_FTYPE_FILE ) {
454     #
455     # Regular file: write the header and file
456     #
457     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
458     if ( !defined($f) ) {
459     print(STDERR "Unable to open file $hdr->{fullPath}\n");
460     $ErrorCnt++;
461     return;
462     }
463     TarWriteFileInfo($fh, $hdr);
464     my($data, $size);
465     while ( $f->read(\$data, $BufSize) > 0 ) {
466     TarWrite($fh, \$data);
467     $size += length($data);
468     }
469     $f->close;
470     TarWritePad($fh, $size);
471     $FileCnt++;
472     $ByteCnt += $size;
473     } elsif ( $hdr->{type} == BPC_FTYPE_HARDLINK ) {
474     #
475     # Hardlink file: either write a hardlink or the complete file
476     # depending upon whether the linked-to file will be written
477     # to the archive.
478     #
479     # Start by reading the contents of the link.
480     #
481     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
482     if ( !defined($f) ) {
483     print(STDERR "Unable to open file $hdr->{fullPath}\n");
484     $ErrorCnt++;
485     return;
486     }
487     my $data;
488     while ( $f->read(\$data, $BufSize) > 0 ) {
489     $hdr->{linkname} .= $data;
490     }
491     $f->close;
492     my $done = 0;
493     my $name = $hdr->{linkname};
494     $name =~ s{^\./}{/};
495     if ( $HardLinkExtraFiles{$name} ) {
496     #
497     # Target file will be or was written, so just remember
498     # the hardlink so we can dump it later.
499     #
500     push(@HardLinks, $hdr);
501     $SpecialCnt++;
502     } else {
503     #
504     # Have to dump the original file. Just call the top-level
505     # routine, so that we save the hassle of dealing with
506     # mangling, merging and attributes.
507     #
508     $HardLinkExtraFiles{$hdr->{linkname}} = 1;
509     archiveWrite($fh, $hdr->{linkname}, $hdr->{name});
510     }
511     } elsif ( $hdr->{type} == BPC_FTYPE_SYMLINK ) {
512     #
513     # Symbolic link: read the symbolic link contents into the header
514     # and write the header.
515     #
516     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0, $hdr->{compress});
517     if ( !defined($f) ) {
518     print(STDERR "Unable to open symlink file $hdr->{fullPath}\n");
519     $ErrorCnt++;
520     return;
521     }
522     my $data;
523     while ( $f->read(\$data, $BufSize) > 0 ) {
524     $hdr->{linkname} .= $data;
525     }
526     $f->close;
527     $hdr->{size} = 0;
528     TarWriteFileInfo($fh, $hdr);
529     $SpecialCnt++;
530     } elsif ( $hdr->{type} == BPC_FTYPE_CHARDEV
531     || $hdr->{type} == BPC_FTYPE_BLOCKDEV
532     || $hdr->{type} == BPC_FTYPE_FIFO ) {
533     #
534     # Special files: for char and block special we read the
535     # major and minor numbers from a plain file.
536     #
537     if ( $hdr->{type} != BPC_FTYPE_FIFO ) {
538     my $f = BackupPC::FileZIO->open($hdr->{fullPath}, 0,
539     $hdr->{compress});
540     my $data;
541     if ( !defined($f) || $f->read(\$data, $BufSize) < 0 ) {
542     print(STDERR "Unable to open/read char/block special file"
543     . " $hdr->{fullPath}\n");
544     $f->close if ( defined($f) );
545     $ErrorCnt++;
546     return;
547     }
548     $f->close;
549     if ( $data =~ /(\d+),(\d+)/ ) {
550     $hdr->{devmajor} = $1;
551     $hdr->{devminor} = $2;
552     }
553     }
554     $hdr->{size} = 0;
555     TarWriteFileInfo($fh, $hdr);
556     $SpecialCnt++;
557     } else {
558     print(STDERR "Got unknown type $hdr->{type} for $hdr->{name}\n");
559     $ErrorCnt++;
560     }
561     }
562 dpavlin 112
563     my $t_fmt = '%Y-%m-%d %H:%M:%S';
564     sub curr_time {
565     return strftime($t_fmt,localtime());
566     }

Properties

Name Value
svn:executable *

  ViewVC Help
Powered by ViewVC 1.1.26