make check_archive transactionally safe
[BackupPC.git] / bin / BackupPC_ASA_BurnArchiveMedia
1 #!/usr/local/bin/perl
2
3 use strict;
4
5 use lib "/usr/local/BackupPC/lib";
6
7 use DBI;
8 use BackupPC::Lib;
9 use BackupPC::Search;
10 use Time::HiRes qw/time/;
11 use POSIX qw/strftime/;
12 use Term::Menus;
13 use File::Which;
14 use File::Path;
15 use Cwd qw/abs_path/;
16 use Data::Dumper;
17
18 my $debug = $ENV{DEBUG} || 1;
19 # set this to 1 to prompt for DVD removal for each selected item.
20 my $prompt_for_delete = shift @ARGV;
21 $|=1;
22
23 # don't check for user
24 my $bpc = BackupPC::Lib->new(undef, undef, 1) || die;
25 $bpc->ConfigRead('_search_archive');
26 my %Conf = $bpc->Conf();
27 %BackupPC::Search::Conf = %Conf;
28
29 my $conf_bin;
30
31 $conf_bin->{'cdrecord'} = $Conf{CDRecordBin} || die "Need CDRecordBin in config.pl\n";
32 my $cdr_opts = $Conf{CDRecordOpts} || die "Need CDRecordOpts in config.pl\n";
33 $conf_bin->{'eject'} = $Conf{ejectBin} || die "Need ejectBin in config.pl\n";
34 my $eject_opts = $Conf{ejectOpts} || die "Need ejectOpts in config.pl\n";
35 $conf_bin->{'mkisofs'} = $Conf{mkisofsBin} || die "Need mkisofsBin in config.pl\n";
36
37 my $path = abs_path($0);
38 $path =~ s#/[^/]+$#/#;
39 my $tarIncCreate = $path .= 'BackupPC_tarIncCreate';
40
41 my $bin;
42 foreach my $c (qw/cdrecord eject mkisofs/) {
43         $bin->{$c} = which($conf_bin->{$c}) || die "$0 needs $c ($conf_bin->{$c}), install it\n";
44 }
45
46 my $start_t = time();
47
48 my $t_fmt = '%Y-%m-%d %H:%M:%S';
49
50
51 my $dsn = $Conf{SearchDSN} || die "Need SearchDSN in config.pl\n";
52 my $user = $Conf{SearchUser} || '';
53
54 my $dbh = DBI->connect($dsn, $user, "", { RaiseError => 1, AutoCommit => 1 });
55
56 my $tar_dir = $Conf{ArchiveDest} || die "ArchiveDest isn't defined in configuration";
57
58 #die "problem with $tar_dir, check GzipTempDir in configuration\n" unless -d $tar_dir;
59
60 my $iso_dir = $Conf{ArchiveDest}.'/iso';
61 if ( ! -e $iso_dir ) {
62         mkdir $iso_dir || die "can't create $iso_dir: $!";
63 }
64
65 #---- subs ----
66
67 sub df_bytes_available {
68         my $path = shift;
69         my $out = `df -P $path`;
70         my $bytes = (split(/\s+/, (split(/\n/,$out))[-1]))[3];
71         return $bytes * 1024;
72
73 }
74
75 sub fmt_time {
76         my $t = shift || return;
77         my $out = "";
78         my ($ss,$mm,$hh) = gmtime($t);
79         $out .= "${hh}h" if ($hh);
80         $out .= sprintf("%02d:%02d", $mm,$ss);
81         return $out;
82 }
83
84 sub curr_time {
85         return strftime($t_fmt,localtime());
86 }
87
88 sub dumpArchive2XML($$$)
89 {
90         my ($dbh, $dvd_nr, $filename) = @_;
91         my %archive;
92
93         my $output = new IO::File('> '.$filename.'.tmp');
94         my $writer = new XML::Writer(OUTPUT=>$output, NEWLINES => 1);
95
96         print "Dumping file list for DVD $dvd_nr, countdown:";
97
98         $writer->pi('xml-stylesheet', 'href="archive.css" type="text/css"');
99
100         my $files_sql = q{
101                 SELECT 
102                         files.path AS path,
103                         files.date AS date,
104                         files.type AS type,
105                         files.size AS size
106                 FROM files, backups, shares
107                 WHERE files.backupnum=backups.num AND
108                         files.shareid=shares.id AND
109                         shares.hostid=backups.hostid AND
110                         backups.id=?
111         };
112
113         my $backups_sql = q{
114                 SELECT
115                         backup_id,
116                         backup_part_id,
117                         host,
118                         num,
119                         date,
120                         share,
121                         size
122                 FROM archive_backup_parts
123                 WHERE archive_id = ?
124                 ORDER BY backup_part_id
125         };
126
127         my $sth = $dbh->prepare("SELECT dvd_nr, total_size, note, username, date, id FROM archive WHERE dvd_nr=?");
128         $sth->execute($dvd_nr);
129         my $row = $sth->fetchrow_hashref();
130
131         my $row_h;
132         foreach my $hide (qw/id note/) {
133                 $row_h->{$hide} = $row->{$hide} || '';
134                 delete $row->{$hide};
135         }
136
137         $writer->startTag("archive", %{$row});
138
139         $writer->startTag("note");
140         $writer->characters( $row_h->{'note'} );
141         $writer->endTag("note");
142
143         my $sth_backups = $dbh->prepare( $backups_sql );
144         $sth_backups->execute( $row_h->{'id'} );
145
146         my $total_backups = $sth_backups->rows;
147         my $curr_backup = 0;
148         my $last_pcnt = 0;
149
150         while (my $row = $sth_backups->fetchrow_hashref()) {
151
152                 $curr_backup++;
153                 my $pcnt = int(($curr_backup * 10) / $total_backups);
154                 if ($pcnt > $last_pcnt) {
155                         print " ",(10 - $pcnt);
156                         $last_pcnt = $pcnt;
157                 }
158
159                 my $sth_files = $dbh->prepare( $files_sql);
160                 $sth_files->execute($row->{'backup_id'});
161
162                 delete($row->{'backup_id'});
163                 $row->{'date'} = strftime($t_fmt,gmtime($row->{'date'}));
164
165                 $writer->startTag( "backup", %{$row} );
166
167                 while (my $row = $sth_files->fetchrow_hashref()) {
168                         # convert filetype to string
169                         $row->{'type'} = BackupPC::Attrib::fileType2Text(undef, $row->{'type'});
170                         $row->{'date'} = strftime($t_fmt,gmtime($row->{'date'}));
171                         my $path = $row->{'path'}; delete $row->{'path'};
172
173                         $writer->startTag("file", %{$row});
174                         $writer->characters( $path );
175                         $writer->endTag("file");
176                 }
177                 $writer->endTag("backup");
178         }
179                          
180         $writer->endTag("archive");
181         $writer->end(); 
182
183         rename $filename.'.tmp', $filename || die "can't rename $filename: $!";
184
185         print "\n";
186 }
187
188
189
190 #----- main
191
192 my $sth = $dbh->prepare( qq{
193 select
194         id,dvd_nr,total_size,note,username,
195         archive.date as date,
196         count(archive_burned.archive_id) as copies
197 from archive
198         left outer join archive_burned on archive.id=archive_burned.archive_id
199 group by id,dvd_nr,total_size,note,username,archive.date
200 order by date asc
201 } );
202
203 $sth->execute();
204
205 sub fmt_mb($) {
206         my $s = shift;
207         die "missing size" unless defined($s);
208         $s /= (1024*1024);
209         return sprintf("%.2f Mb", $s);
210 }
211
212 sub fmt_archive($) {
213         my $row = shift || die;
214
215         $row->{'date'} =~ s/\.\d+$//;
216         $row->{'copies'} =~ s/^\s*0+\s*$/no/;
217
218         my $copies = 'copies';
219         $copies = 'copy' if ($row->{'copies'} == 1);
220
221         return
222                 sprintf("%d by %s on %s, %s %s [%s]",
223                         $row->{'dvd_nr'},
224                         $row->{'username'},
225                         $row->{'date'},
226                         $row->{'copies'}, $copies,
227                         fmt_mb($row->{'total_size'}),
228                 );
229 }
230
231 my @burned;
232 my @not_burned;
233
234 while (my $row = $sth->fetchrow_hashref) {
235         if ($row->{'copies'}) {
236                 push @burned, fmt_archive($row);
237         } else {
238                 push @not_burned, fmt_archive($row);
239         }
240 }
241
242 my %Menu_archive = (
243         Label => 'Menu_archive',
244
245         Item_1 => {
246                 Text => 'DVD #]Convey[',
247                 Convey => [ @not_burned ],
248                 Default => '*',
249         },
250         Item_2 => {
251                 Text => 'DVD #]Convey[',
252                 Convey => [ @burned ],
253         },
254
255         Select => 'Many',
256
257         Banner => "Select one or more DVD media for burning",
258 );
259
260 my @archives_to_burn = Menu(\%Menu_archive);
261
262 print "\n";
263
264 sub skip($) {
265         my $msg = shift;
266         print "WARNING: $msg, skipping...\n";
267         goto SKIP;
268 }
269
270 sub add_symlink($$) {
271         my ($from, $to) = @_;
272         symlink $from, $to || skip("can't symlink $from to $to: $!");
273 }
274
275 sub delete_dvd($) {
276         my $dvd_nr = shift || return;
277
278         print "Do you want to delete DVD #$dvd_nr now? [NO/yes]: ";
279         my $ok = <STDIN>;
280         chomp($ok);
281         if (lc($ok) eq 'yes') {
282                 print "Deleting DVD #$dvd_nr from database...\n";
283
284                 $dbh->begin_work;
285
286                 my $sth_delete_dvd = $dbh->prepare( qq{
287                         delete from archive where dvd_nr = ?
288                 } );
289                 $sth_delete_dvd->execute( $dvd_nr );
290                 $dbh->do( qq{
291                         select setval('dvd_nr', (select max(dvd_nr) from archive), true)
292                 } );
293
294                 # remove files for this DVD
295                 map {
296                         if (-d $_) {
297                                 print "\tremoving dir $_\n";
298                                 rmtree($_) || die "can't rmtree $_: $!";
299                         } else {
300                                 print "\tremoving $_\n";
301                                 unlink($_) || die "can't rm $_: $!";
302                         }
303                 } glob ( "/$iso_dir/$dvd_nr.*" );
304
305                 $dbh->commit;
306
307                 return 1;
308         } else {
309                 return 0;
310         }
311 }
312
313 my $sth_archive_backup_parts = $dbh->prepare( qq{
314         SELECT
315                 backup_id,
316                 archive_id,
317                 host,
318                 share,
319                 num,
320                 part_nr,
321                 parts,
322                 size,
323                 md5,
324                 items,
325                 filename
326         FROM archive_backup_parts
327         WHERE dvd_nr = ?
328         ORDER BY backup_id, part_nr
329 });
330
331 my $sth_archive_burned = $dbh->prepare( qq{
332         insert into archive_burned
333                 (archive_id, iso_size, part, copy)
334         values ( (select id from archive where dvd_nr =?), ?, ?, ?)
335 });
336
337 my $copies = $Conf{BurnMultipleCopies} || 1;
338
339 foreach my $copy_nr ( 1 .. $copies ) {
340
341         foreach my $arc (@archives_to_burn) {
342                 exit if ($arc eq ']quit[');
343
344                 my $dvd_nr = $1 if ($arc =~ m/DVD #(\d+)/);
345                 die "BUG: can't find dvd_nr in $arc\n" unless ($dvd_nr);
346
347                 my $tmp_dir = "/$iso_dir/$dvd_nr";
348
349                 my $t = time();
350
351                 print "Working on DVD #$dvd_nr in $tmp_dir\n";
352
353                 $sth_archive_backup_parts->execute($dvd_nr);
354
355                 if ($sth_archive_backup_parts->rows == 0) {
356                         warn "ERROR: no backup parts found for $dvd_nr. You should re-create that DVD.\n";
357                         next if delete_dvd( $dvd_nr );
358                 }
359
360                 if ($prompt_for_delete) {
361                         next if delete_dvd( $dvd_nr );
362                 }
363
364                 my @volumes;
365                 my $v;  # emtpy volume
366                 my $v_size = 0;
367
368                 my $max_archive_size = $Conf{ArchiveMediaSize} || die "no ArchiveMediaSize";
369                 while (my $row = $sth_archive_backup_parts->fetchrow_hashref) {
370                         if (($v->{size} || 0) + $row->{size} > $max_archive_size) {
371                                 push @volumes, $v;
372                                 $v = {};
373                         }
374                         $v->{size} += $row->{size};
375                         $v_size += $row->{size};
376
377                         # this part
378                         my $p;
379                         $p->{$_} = $row->{$_} foreach (qw(
380                                 filename host share num part_nr md5
381                         )); # include minimun number of columns in XML output
382
383                         push @{ $v->{parts} }, $p;
384                 }
385                 push @volumes, $v if ($v);
386
387                 warn "# volumes: ",Dumper(\@volumes)," total size: ", fmt_mb($v_size), "\n" if $debug;
388
389                 # check available disk space
390
391                 my $df = df_bytes_available($iso_dir);
392                 if ($df < $v_size) {
393                         warn "ABORTED: not enough disk space to create ISO ! [need ", fmt_mb($v_size), " have ", fmt_mb( $df ), " on $iso_dir]\n";
394                         next;
395                 }
396
397                 my $volumes = $#volumes + 1;
398                 my $volume_nr = 1;
399
400                 foreach my $v (@volumes) {
401
402                         #print Dumper($v);
403
404                         my $iso_size = 0;
405                         my $disk_name = $dvd_nr;
406                         # suffix added to multi-volume archives
407                         my $volume_suffix = '';
408
409                         if ($volumes > 1) {
410                                 $volume_suffix = '_' . $volume_nr;
411                                 $disk_name .= ' ' . $volume_nr . '/' . $volumes;
412                         }
413
414                         print "Processing DVD #$dvd_nr, volume $volume_nr/$volumes [", fmt_mb($v->{size}), "]\n";
415
416                         my $iso_file = my $xml_file = my $stage =
417                                 "${iso_dir}/${dvd_nr}";
418
419                         $iso_file .= $volume_suffix . '.iso';
420                         $xml_file .= '.xml';
421
422                         $stage .= $volume_suffix . '.stage';
423
424                         my $md5_file = "${stage}/${dvd_nr}${volume_suffix}.md5";
425
426                         #
427                         # check if ISO file exists
428                         #
429
430                         if (! -e $iso_file) {
431
432                                 # create stage directory
433                                 if (-e $stage) {
434                                         rmtree($stage) || die "can't remove $stage: $!";
435                                 }
436                                 mkpath($stage);
437
438                                 # open file for md5sums
439                                 open(my $md5, "> $md5_file") || skip "can't open $md5_file: $!";
440
441                                 my $parts_on_this_volume = 0;
442
443                                 foreach my $p (@{ $v->{parts} }) {
444                                         my $tar_file = $p->{filename} || die "no filename in part", Dumper($p);
445                                         
446                                         die "ERROR: increment missing $tar_file:$!" unless -r "$tar_dir/$tar_file";
447
448                                         add_symlink("$tar_dir/$tar_file", "$stage/$tar_file");
449
450                                         my $md5sum = $p->{md5} || die "no md5 in part ", Dumper($p);
451                                         chomp($md5sum);
452                                         print $md5 "$md5sum  $tar_file\n" || die "can't write md5sum: $!";
453
454                                         $parts_on_this_volume++;
455                                 }
456
457                                 # add file list and note in xml
458                                 dumpArchive2XML($dbh, $dvd_nr, $xml_file) unless (-f $xml_file);
459
460                                 add_symlink($xml_file, "$stage/${dvd_nr}.xml");
461
462                                 # add css file for archive
463                                 my $css_file = $Conf{CgiImageDir} . '/archive.css';
464                                 if (-r $css_file) {
465                                         add_symlink($css_file, "$stage/archive.css");
466                                 } else {
467                                         print "WARNING: missing $css_file, not added to iso image!\n";
468                                 }
469
470                                 print "Running mkisofs now for $parts_on_this_volume increments, disk $disk_name\n";
471
472                                 my $cmd = $bin->{'mkisofs'} . qq{ -A BackupPC -gui -J -r -T --input-charset ISO-8859-2 -V "$disk_name" -o ${iso_file}.tmp -f $stage };
473
474                                 system($cmd) == 0 or skip "can't run $cmd: $?";
475
476                                 rename $iso_file.'.tmp', $iso_file || skip "can't rename $iso_file: $!";
477
478                                 $iso_size = (stat($iso_file))[7];
479
480                                 print "Created $iso_file [$iso_size bytes] in ", fmt_time(time() - $t), "\n";
481
482                                 rmtree($stage) || warn "can't remove stage directory $stage: $!";
483
484                         } else {
485                                 $iso_size = (stat($iso_file))[7];
486                                 print "ISO $iso_file already exists [$iso_size bytes]\n";
487                         }
488
489                         print "\nREADY TO BURN MEDIA $disk_name copy $copy_nr\n\nPlease insert blank media and press ENTER\n\n";
490
491                         system($bin->{'eject'}.' '.$eject_opts) == 0 or skip "can't run eject: $?";
492
493                         my $wait = <STDIN>;
494
495                         my $cmd = $bin->{'cdrecord'} . ' ' . $cdr_opts . ' ' . $iso_file;
496
497                         # FIXME
498                         print "## $cmd\n";
499                         system($cmd) == 0 or skip "can't run $cmd: $?";
500
501                         print "\n\nPLEASE REMOVE DVD MEDIA AND LABEL IT WITH $disk_name\n\n";
502
503                         $sth_archive_burned->execute($dvd_nr, $iso_size, $volume_nr, $copy_nr);
504
505                         print "Media burn for $disk_name copy $copy_nr recorded\n";
506
507                         if ($copy_nr >= $copies) {
508                                 print STDERR "erasing temporary files, have $copy_nr copies (> $copies)\n";
509                                 foreach my $f (( $xml_file, $iso_file )) {
510                                         print STDERR "\t$f ";
511                                         unlink $f || die "can't remove $f: $!";
512                                         print STDERR "removed\n";
513                                 }
514                         }
515
516                         $volume_nr++;
517                 }
518
519         }
520
521 SKIP:
522
523 }
524
525 #my $tar_file = BackupPC::Search::getGzipName($row->{'host'}, $row->{'share'}, $row->{'num'});
526 #print curr_time, sprintf(" %s:%s %-3d ", $row->{'host'}, $row->{'share'}, $row->{'num'}), " -> $tar_file ";
527
528 print "Recoding finished, exiting...\n";
529
530 $sth->finish;
531 $sth_archive_backup_parts->finish;
532 $sth_archive_burned->finish;
533 $sth_archive_burned->finish;
534
535 $dbh->disconnect;
536