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