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