first version which stores backup parts
[BackupPC.git] / bin / BackupPC_ASA_PostArchive_Update
1 #!/usr/local/bin/perl -w
2
3 use strict;
4 use lib "/usr/local/BackupPC/lib";
5
6 use DBI;
7 use BackupPC::Lib;
8 use BackupPC::View;
9 use BackupPC::Attrib qw/:all/;
10 use Data::Dump qw(dump);
11 use Time::HiRes qw/time/;
12 use POSIX qw/strftime/;
13 use Cwd qw/abs_path/;
14 use Archive::Tar::Streamed;
15 use Algorithm::Diff;
16 use Getopt::Std;
17 use File::Slurp;
18
19 =head1 NAME
20
21 BackupPC_ASA_PostArchive_Update
22
23 =head1 DESCRIPTION
24
25         # /etc/BackupPC/pc/dvd_tar.pl
26
27 =cut
28
29 # FIXME
30 my $debug = $ENV{DEBUG} || 1;
31 my $check = $ENV{CHECK} || 1;
32
33
34 my $bpc = BackupPC::Lib->new || die "can't create BackupPC::Lib";
35 my %Conf = $bpc->Conf();
36 warn "## ARGV=",dump @ARGV;
37
38
39 my $args;
40 my $name;
41 foreach ( @ARGV ) {
42         my $v = $_;
43         if ( m/(\w+)=(.+)/ ) {
44                 $name = $1;
45                 $v = $2;
46         }
47         if ( $name =~ m/List/ ) {
48                 push @{ $args->{$name} }, $v;
49         } else {
50                 $args->{$name} = $v;
51         }
52 }
53
54 warn "args = ",dump($args);
55
56
57 use BackupPC::Search;
58 %BackupPC::Search::Conf = %Conf;
59
60 my $path = abs_path($0);
61 $path =~ s{/[^/]+$}{/}; # FIXME remove?
62
63 $|=1;
64
65 my $start_t = time();
66
67 my $t_fmt = '%Y-%m-%d %H:%M:%S';
68
69 warn "## Conf = ",dump( \%Conf );
70
71 my $dsn = $Conf{SearchDSN} || die "Need SearchDSN in config.pl\n";
72 my $user = $Conf{SearchUser} || '';
73
74 my $dbh = DBI->connect($Conf{SearchDSN}, $Conf{SearchUser}, "", { RaiseError => 1, AutoCommit => 0 });
75
76 #---- subs ----
77
78
79 sub curr_time {
80         return strftime($t_fmt,localtime());
81 }
82
83 sub fmt_time {
84         my $t = shift || return;
85         my $out = "";
86         my ($ss,$mm,$hh) = gmtime($t);
87         $out .= "${hh}h" if ($hh);
88         $out .= sprintf("%02d:%02d", $mm,$ss);
89         return $out;
90 }
91
92 my $hsn_cache;
93
94 sub get_backup_id($$) {
95         my ($host, $num) = @_;
96
97         my $key = "$host $num";
98         return $hsn_cache->{$key} if ($hsn_cache->{$key});
99
100         my $sth = $dbh->prepare(qq{
101                 SELECT 
102                         backups.id
103                 FROM backups 
104                 INNER JOIN shares       ON backups.shareID=shares.ID
105                 INNER JOIN hosts        ON backups.hostID = hosts.ID
106                 WHERE hosts.name = ? and backups.num = ?
107         });
108         $sth->execute($host, $num);
109         my ($id) = $sth->fetchrow_array;
110
111         $hsn_cache->{"$host $num"} = $id;
112
113         print STDERR "# $host $num == $id\n" if $debug;
114
115         return $id;
116 }
117
118 sub backup_inc_deleted($) {
119         my $backup_id = shift;
120         my $sth_inc_deleted = $dbh->prepare(qq{
121                 update backups set
122                         inc_deleted = true
123                 where id = ?
124         });
125         $sth_inc_deleted->execute($backup_id);
126 }
127
128 sub system_ok {
129         warn "## system_ok @_\n";
130         system(@_) == 0 || die "system @_:$!";
131 }
132
133 sub check_archive {
134         my ($host,$num) = @_;
135
136         my $t = time();
137
138         my @tar_parts =
139                 sort map { s/^\Q$Conf{ArchiveDest}\E\/*//; $_ }
140                 glob "$Conf{ArchiveDest}/$host.$num.*"
141                 ;
142
143         return unless @tar_parts;
144
145         print curr_time, " check $host $num";
146
147         my $md5_path = "$Conf{ArchiveDest}/$host.$num.md5";
148         unlink $md5_path if -s $md5_path == 0; # fix empty
149
150         if ( ! -e $md5_path ) {
151                 system_ok "cd $Conf{ArchiveDest} && /usr/bin/md5sum $host.$num.* > $md5_path";
152         } else {
153                 system_ok "cd $Conf{ArchiveDest} && /usr/bin/md5sum -c $md5_path" if $check;
154         }
155
156         my $md5sum;
157         foreach ( split(/\n/, read_file "$Conf{ArchiveDest}/$host.$num.md5" ) ) {
158                 my ( $md5, $path ) = split(/\s+/,$_);
159                 $md5sum->{$path} = $md5;
160         }
161
162         # depending on expected returned value this is used like:
163         # my $uncompress_size = get_gzip_size('/full/path/to.gz');
164         # my ($compress_size, $uncompress_size) = get_gzip_size('/path.gz');
165         sub get_gzip_size($) {
166                 my $filename = shift;
167                 die "file $filename problem: $!" unless (-r $filename);
168
169                 if ( $filename !~ m/\.gz$/ ) {
170                         return -s $filename;
171                 }
172
173                 open(my $gzip, $Conf{GzipPath}." -l $filename |") || die "can't gzip -l $filename: $!";
174                 my $line = <$gzip>;
175                 chomp($line);
176                 $line = <$gzip> if ($line =~ /^\s+compressed/);
177
178                 my ($comp, $uncomp) = (0,0);
179
180                 if ($line =~ m/^\s+(\d+)\s+(\d+)\s+\d+\.\d+/) {
181                         if (wantarray) {
182                                 return [ $1, $2 ];
183                         } else {
184                                 return $2;
185                         }
186                 } else {
187                         die "can't find size in line: $line";
188                 }
189         }
190
191         sub check_part {
192                 my ($host, $num, $part_nr, $tar_size, $size, $md5, $items) = @_;
193                 my $backup_id = get_backup_id($host, $num);
194                 my $sth_md5 = $dbh->prepare(qq{
195                         select
196                                 id, tar_size, size, md5, items
197                         from backup_parts
198                         where backup_id = ? and part_nr = ?
199                 });
200
201                 $sth_md5->execute($backup_id, $part_nr);
202
203                 if (my $row = $sth_md5->fetchrow_hashref) {
204                         return if (
205                                 $row->{tar_size} >= $tar_size &&
206                                 $row->{size} == $size &&
207                                 $row->{md5} eq $md5 &&
208                                 $row->{items} == $items
209                         );
210                         print ", deleting invalid backup_parts $row->{id}";
211                         $dbh->do(qq{ delete from backup_parts where id = $row->{id} });
212                 }
213                 print ", inserting new";
214                 my $sth_insert = $dbh->prepare(qq{
215                         insert into backup_parts (
216                                 backup_id,
217                                 part_nr,
218                                 tar_size,
219                                 size,
220                                 md5,
221                                 items
222                         ) values (?,?,?,?,?,?)
223                 });
224
225                 $sth_insert->execute($backup_id, $part_nr, $tar_size, $size, $md5, $items);
226                 $dbh->commit;
227         }
228
229         print " [parts: ",join(", ", @tar_parts),"]" if $debug;
230
231         my $same = 1;
232         my @tar_files;
233
234         my $backup_part;
235
236         print " reading" if $debug;
237
238         my $part_nr = 1;
239
240         foreach my $filename (@tar_parts) {
241
242                 next if $filename eq "$host.$num.md5";
243
244                 print "\n\t- $filename";
245
246                 my $path = "$Conf{ArchiveDest}/$filename";
247                 $path =~ s{//+}{/}g;
248
249                 my $size = (stat( $path ))[7] || die "can't stat $path: $!";
250
251                 if ($size > $Conf{MaxArchiveSize}) {
252                         print ", part bigger than media $size > $Conf{MaxArchiveSize}\n";
253                         return 0;
254                 }
255
256                 print ", $size bytes";
257
258 =for later
259
260                 open(my $fh, "gzip -cd $path |") or die "can't open $path: $!";
261                 binmode($fh);
262                 my $tar = Archive::Tar::Streamed->new($fh);
263
264                 my $tar_size_inarc = 0;
265                 my $items = 0;
266
267                 while(my $entry = $tar->next) {
268                         push @tar_files, $entry->name;
269                         $items++;
270                         $tar_size_inarc += $entry->size;
271
272                         if ($tar_size_inarc > $Conf{MaxArchiveFileSize}) {
273                                 print ", part $filename is too big $tar_size_inarc > $Conf{MaxArchiveFileSize}\n";
274                                 return 0;
275                         }
276
277                 }
278
279                 close($fh);
280
281                 print ", $items items";
282
283                 if ($tar_size_inarc == 0 && $items == 0) {
284                         print ", EMPTY tar\n";
285
286                         my $backup_id = get_backup_id($host, $share, $num);
287                         backup_inc_deleted( $backup_id );
288
289                         $dbh->commit;
290
291                         return 1;
292                 }
293
294 =cut
295
296                 # FIXME
297                 my $tar_size = get_gzip_size( $path );
298
299                 #
300                 # finally, check if backup_parts table in database is valid
301                 #
302
303                 my $md5 = $md5sum->{$filename} || die "no md5sum for $filename in ",dump($md5sum);
304                 my $items = 1;
305
306                 check_part($host, $num, $part_nr, $tar_size, $size, $md5, $items);
307
308                 $part_nr++;
309         }
310
311         # short-cut and exit;
312         return $same unless($same);
313
314         @tar_files = sort @tar_files;
315         print "\n\t",($#tar_files + 1), " tar files";
316
317         my $sth = $dbh->prepare(qq{
318                 SELECT path,type
319                 FROM files
320                 JOIN shares on shares.id = shareid
321                 JOIN hosts on hosts.id = shares.hostid
322                 WHERE hosts.name = ? and backupnum = ?
323         });
324         $sth->execute($host, $num);
325         my @db_files;
326         while( my $row = $sth->fetchrow_hashref ) {
327
328                 my $path = $row->{'path'} || die "no path?";
329                 $path =~ s#^/#./#;
330                 $path .= '/' if ($row->{'type'} == BPC_FTYPE_DIR);
331                 push @db_files, $path;
332         }
333
334         print " ",($#db_files + 1), " database files, diff";
335
336         @db_files = sort @db_files;
337
338         if ($#tar_files != $#db_files) {
339                 $same = 0;
340                 print " NUMBER";
341         } else {
342                 my $diff = Algorithm::Diff->new(\@tar_files, \@db_files);
343                 while ( $diff->Next() ) {
344                         next if $diff->Same();
345                         $same = 0;
346                         print "< $_\n" for $diff->Items(1);
347                         print "> $_\n" for $diff->Items(2);
348                 }
349         }
350
351         print " ",($same ? 'ok' : 'DIFFERENT'),
352                 ", dur: ",fmt_time(time() - $t), "\n";
353
354         return $same;
355 }
356
357
358 #----- main
359
360 foreach ( 0 .. $#{ $args->{HostList} } ) {
361
362         my $host = $args->{'HostList'}->[$_];
363         my $num  = $args->{'BackupList'}->[$_];
364
365         check_archive $host => $num;
366
367 }
368
369 exit;
370
371 my $sth = $dbh->prepare( qq{
372         
373 select
374         backups.id as backup_id,
375         hosts.name as host,
376         shares.name as share,
377         backups.num as num,
378         backups.date,
379         inc_size,
380         parts,
381         count(backup_parts.backup_id) as backup_parts
382 from backups
383         join shares on backups.hostid = shares.hostid
384                 and shares.id = backups.shareid
385         join hosts on shares.hostid = hosts.id
386         full outer join backup_parts on backups.id = backup_parts.backup_id
387 where not inc_deleted and backups.size > 0
388 group by backups.id, hosts.name, shares.name, backups.num, backups.date, inc_size, parts, backup_parts.backup_id
389 order by backups.date
390
391 } );
392
393 $sth->execute();
394 my $num_backups = $sth->rows;
395 my $curr_backup = 1;
396
397 while (my $row = $sth->fetchrow_hashref) {
398
399         $curr_backup++;
400
401         my $tar_file = BackupPC::Search::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'});
402
403         # this will return -1 if file doesn't exist
404         my $size = BackupPC::Search::get_tgz_size_by_name($tar_file);
405
406         print "# host: ".$row->{host}.", share: ".$row->{'share'}.", backup_num:".$row->{num}." size: $size backup.size: ", $row->{inc_size},"\n" if $debug;
407
408         if ( $row->{'inc_size'} != -1 && $size != -1 && $row->{'inc_size'} >= $size && $row->{parts} == $row->{backup_parts}) {
409                 if ($check) {
410                         tar_check($row->{'host'}, $row->{'share'}, $row->{'num'}, $tar_file) && next;
411                 } else {
412                         next;
413                 }
414         }
415
416         print curr_time, " creating $curr_backup/$num_backups ", $row->{host}, ":", $row->{share}, " #", $row->{num},
417                 " ", strftime('%Y-%m-%d', localtime($row->{date})), " -> $tar_file";
418
419         my $t = time();
420
421 =for later
422         # re-create archive?
423         my $cmd = qq[ $tarIncCreate -h "$row->{host}" -s "$row->{share}" -n $row->{num} -f ];
424         print STDERR "## $cmd\n" if ($debug);
425
426         if (system($cmd) != 0) {
427                 print STDERR " FAILED, marking this backup deleted";
428                 backup_inc_deleted( $row->{backup_id} );
429         }
430 =cut
431
432         print ", dur: ",fmt_time(time() - $t), "\n";
433
434         $dbh->commit;
435
436 }
437
438 undef $sth;
439 $dbh->disconnect;