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