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