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