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