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