make md5sums read-only
[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 [ 'check|c',    "check archives on disk and sync", { default => 1 } ],
42 [ 'debug|d',    "debug", { default => 1 } ],
43 [ 'help',       "show help" ],
44 );
45
46 print($usage->text), exit if $opt->help;
47
48 $|=1;
49
50 my $start_t = time();
51
52 my $t_fmt = '%Y-%m-%d %H:%M:%S';
53
54 #warn "## Conf = ",dump( \%Conf );
55
56 my $dbh = DBI->connect($Conf{SearchDSN}, $Conf{SearchUser}, "", { RaiseError => 1, AutoCommit => 0 });
57
58 #---- subs ----
59
60
61 sub curr_time {
62         return strftime($t_fmt,localtime());
63 }
64
65 sub fmt_time {
66         my $t = shift || return;
67         my $out = "";
68         my ($ss,$mm,$hh) = gmtime($t);
69         $out .= "${hh}h" if ($hh);
70         $out .= sprintf("%02d:%02d", $mm,$ss);
71         return $out;
72 }
73
74 my $hsn_cache;
75
76 sub get_backup_id($$) {
77         my ($host, $num) = @_;
78
79         my $key = "$host $num";
80         return $hsn_cache->{$key} if ($hsn_cache->{$key});
81
82         my $sth = $dbh->prepare(qq{
83                 SELECT 
84                         backups.id
85                 FROM backups 
86                 INNER JOIN shares       ON backups.shareID=shares.ID
87                 INNER JOIN hosts        ON backups.hostID = hosts.ID
88                 WHERE hosts.name = ? and backups.num = ?
89         });
90         $sth->execute($host, $num);
91         my ($id) = $sth->fetchrow_array;
92
93         $hsn_cache->{"$host $num"} = $id;
94
95         print STDERR "# $host $num == $id\n" if $opt->debug;
96
97         return $id;
98 }
99
100 sub backup_inc_deleted($) {
101         my $backup_id = shift;
102         my $sth_inc_deleted = $dbh->prepare(qq{
103                 update backups set
104                         inc_deleted = true
105                 where id = ?
106         });
107         $sth_inc_deleted->execute($backup_id);
108 }
109
110 sub system_ok {
111         warn "## system_ok @_\n";
112         system(@_) == 0 || die "system @_:$!";
113 }
114
115 my $sth_inc_size = $dbh->prepare(qq{
116         update backups set
117                 inc_size = ?,
118                 parts = ?,
119                 inc_deleted = false
120         where id = ?
121 });
122
123 sub read_only {
124         my $full = shift;
125         my $perm = (stat $full)[2] & 0444;
126         warn sprintf("chmod %03o %s\n",$perm,$full);
127         chmod $perm, $full || die $!;
128 }
129
130 sub check_archive {
131         my ($host,$num) = @_;
132         warn "# check_archive $host $num";
133
134         my $t = time();
135
136         my $glob = "$Conf{ArchiveDest}/$host.$num.*";
137
138         my @tar_parts = sort map { s/^\Q$Conf{ArchiveDest}\E\/*//; $_ } glob $glob ;
139
140         if ( ! @tar_parts ) {
141                 warn "ERROR: no files for $glob";
142                 return;
143         }
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         my $read_protect = 0;
151
152         if ( ! -e $md5_path ) {
153                 system_ok "cd $Conf{ArchiveDest} && /usr/bin/md5sum $host.$num.* > $md5_path";
154                 read_only $md5_path;
155                 $read_protect = 1;
156         } else {
157                 system_ok "cd $Conf{ArchiveDest} && /usr/bin/md5sum -c $md5_path" if $opt->check;
158         }
159
160         my $md5sum;
161         foreach ( split(/\n/, read_file "$Conf{ArchiveDest}/$host.$num.md5" ) ) {
162                 my ( $md5, $path ) = split(/\s+/,$_);
163                 $md5sum->{$path} = $md5;
164                 read_only "$Conf{ArchiveDest}/$path" if $read_protect;
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                 local $/ = undef;
180                 my $line = <$gzip>;
181                 close($gzip);
182
183                 my ($comp, $uncomp) = (0,0);
184
185                 if ($line =~ m/\s+(\d+)\s+(\d+)\s+\d+\.\d+/s) {
186                         if (wantarray) {
187                                 return [ $1, $2 ];
188                         } else {
189                                 return $2;
190                         }
191                 } else {
192                         warn "ERROR can't parse: $line";
193                         return -s $filename;
194                 }
195         }
196
197         sub check_part {
198                 my ($host, $num, $part_nr, $tar_size, $size, $md5, $items, $filename) = @_;
199                 my $backup_id = get_backup_id($host, $num);
200                 my $sth_md5 = $dbh->prepare(qq{
201                         select
202                                 id, tar_size, size, md5, items, filename
203                         from backup_parts
204                         where backup_id = ? and part_nr = ? and filename = ?
205                 });
206
207                 $sth_md5->execute($backup_id, $part_nr, $filename);
208
209                 if (my $row = $sth_md5->fetchrow_hashref) {
210                         return if (
211                                 $row->{tar_size} >= $tar_size &&
212                                 $row->{size} == $size &&
213                                 $row->{md5} eq $md5 &&
214                                 $row->{items} == $items
215                         );
216                         print ", deleting invalid backup_parts $row->{id}";
217                         $dbh->do(qq{ delete from backup_parts where id = $row->{id} });
218                 }
219                 print ", inserting new";
220                 my $sth_insert = $dbh->prepare(qq{
221                         insert into backup_parts (
222                                 backup_id,
223                                 part_nr,
224                                 tar_size,
225                                 size,
226                                 md5,
227                                 items,
228                                 filename
229                         ) values (?,?,?,?,?,?,?)
230                 });
231
232                 $sth_insert->execute($backup_id, $part_nr, $tar_size, $size, $md5, $items, $filename);
233                 $dbh->commit;
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         $dbh->commit;
326
327         @tar_files = sort @tar_files;
328         print "\n\t",($#tar_files + 1), " tar files";
329
330         my $sth = $dbh->prepare(qq{
331                 SELECT path,type
332                 FROM files
333                 JOIN shares on shares.id = shareid
334                 JOIN hosts on hosts.id = shares.hostid
335                 WHERE hosts.name = ? and backupnum = ?
336         });
337         $sth->execute($host, $num);
338         my @db_files;
339         while( my $row = $sth->fetchrow_hashref ) {
340
341                 my $path = $row->{'path'} || die "no path?";
342                 $path =~ s#^/#./#;
343                 $path .= '/' if ($row->{'type'} == BPC_FTYPE_DIR);
344                 push @db_files, $path;
345         }
346
347         print " ",($#db_files + 1), " database files, diff";
348
349         @db_files = sort @db_files;
350
351         my $same = 1;
352
353         if ($#tar_files != $#db_files) {
354                 $same = 0;
355                 print " NUMBER";
356         } else {
357                 my $diff = Algorithm::Diff->new(\@tar_files, \@db_files);
358                 while ( $diff->Next() ) {
359                         next if $diff->Same();
360                         $same = 0;
361                         print "< $_\n" for $diff->Items(1);
362                         print "> $_\n" for $diff->Items(2);
363                 }
364         }
365
366         print " ",($same ? 'ok' : 'DIFFERENT'),
367                 ", dur: ",fmt_time(time() - $t), "\n";
368
369         return $same;
370 }
371
372
373 #----- main
374
375 foreach ( 0 .. $#{ $opt->host } ) {
376
377         my $host = $opt->host->[$_];
378         my $num  = $opt->num->[$_];
379
380         check_archive $host => $num;
381
382 }
383
384 exit; # FIXME
385
386 my $sth = $dbh->prepare( qq{
387         
388 select
389         backups.id as backup_id,
390         hosts.name as host,
391         shares.name as share,
392         backups.num as num,
393         backups.date,
394         inc_size,
395         parts,
396         count(backup_parts.backup_id) as backup_parts
397 from backups
398         join shares on backups.hostid = shares.hostid
399                 and shares.id = backups.shareid
400         join hosts on shares.hostid = hosts.id
401         full outer join backup_parts on backups.id = backup_parts.backup_id
402 where not inc_deleted and backups.size > 0
403 group by backups.id, hosts.name, shares.name, backups.num, backups.date, inc_size, parts, backup_parts.backup_id
404 order by backups.date
405
406 } );
407
408 $sth->execute();
409 my $num_backups = $sth->rows;
410 my $curr_backup = 1;
411
412 while (my $row = $sth->fetchrow_hashref) {
413
414         $curr_backup++;
415
416         my $tar_file = BackupPC::Search::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'});
417
418         # this will return -1 if file doesn't exist
419         my $size = BackupPC::Search::get_tgz_size_by_name($tar_file);
420
421         print "# host: ".$row->{host}.", share: ".$row->{'share'}.", backup_num:".$row->{num}." size: $size backup.size: ", $row->{inc_size},"\n" if $opt->debug;
422
423         if ( $row->{'inc_size'} != -1 && $size != -1 && $row->{'inc_size'} >= $size && $row->{parts} == $row->{backup_parts}) {
424                 if ($opt->check) {
425                         tar_check($row->{'host'}, $row->{'share'}, $row->{'num'}, $tar_file) && next;
426                 } else {
427                         next;
428                 }
429         }
430
431         print curr_time, " creating $curr_backup/$num_backups ", $row->{host}, ":", $row->{share}, " #", $row->{num},
432                 " ", strftime('%Y-%m-%d', localtime($row->{date})), " -> $tar_file";
433
434         my $t = time();
435
436 =for later
437         # re-create archive?
438         my $cmd = qq[ $tarIncCreate -h "$row->{host}" -s "$row->{share}" -n $row->{num} -f ];
439         print STDERR "## $cmd\n" if ($opt->debug);
440
441         if (system($cmd) != 0) {
442                 print STDERR " FAILED, marking this backup deleted";
443                 backup_inc_deleted( $row->{backup_id} );
444         }
445 =cut
446
447         print ", dur: ",fmt_time(time() - $t), "\n";
448
449         $dbh->commit;
450
451 }
452
453 undef $sth;
454 $dbh->disconnect;