]> git.proxmox.com Git - pve-manager.git/blame - PVE/VZDump.pm
add missing use clause
[pve-manager.git] / PVE / VZDump.pm
CommitLineData
aaeeeebe
DM
1package PVE::VZDump;
2
aaeeeebe
DM
3use strict;
4use warnings;
5use Fcntl ':flock';
31aef761 6use PVE::Exception qw(raise_param_exc);
4a4051d8 7use PVE::SafeSyslog;
aaeeeebe
DM
8use IO::File;
9use IO::Select;
10use IPC::Open3;
11use POSIX qw(strftime);
12use File::Path;
98e84b16 13use PVE::RPCEnvironment;
4a4051d8
DM
14use PVE::Storage;
15use PVE::Cluster qw(cfs_read_file);
aaeeeebe
DM
16use PVE::VZDump::OpenVZ;
17use Time::localtime;
18use Time::Local;
ac27b58d 19use PVE::JSONSchema qw(get_standard_option);
aaeeeebe
DM
20
21my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
22
23my $lockfile = '/var/run/vzdump.lock';
24
25my $logdir = '/var/log/vzdump';
26
27my @plugins = qw (PVE::VZDump::OpenVZ);
28
29# Load available plugins
30my $pveplug = "/usr/share/perl5/PVE/VZDump/QemuServer.pm";
31if (-f $pveplug) {
32 eval { require $pveplug; };
33 if (!$@) {
34 PVE::VZDump::QemuServer->import ();
35 push @plugins, "PVE::VZDump::QemuServer";
36 } else {
37 warn $@;
38 }
39}
40
41# helper functions
42
43my $debugstattxt = {
44 err => 'ERROR:',
45 info => 'INFO:',
46 warn => 'WARN:',
47};
48
49sub debugmsg {
50 my ($mtype, $msg, $logfd, $syslog) = @_;
51
52 chomp $msg;
53
54 return if !$msg;
55
56 my $pre = $debugstattxt->{$mtype} || $debugstattxt->{'err'};
57
58 my $timestr = strftime ("%b %d %H:%M:%S", CORE::localtime);
59
60 syslog ($mtype eq 'info' ? 'info' : 'err', "$pre $msg") if $syslog;
61
62 foreach my $line (split (/\n/, $msg)) {
63 print STDERR "$pre $line\n";
64 print $logfd "$timestr $pre $line\n" if $logfd;
65 }
66}
67
68sub run_command {
69 my ($logfd, $cmdstr, %param) = @_;
70
7f910306 71 my $logfunc = sub {
4a4051d8 72 my $line = shift;
4a4051d8 73 debugmsg ('info', $line, $logfd);
aaeeeebe
DM
74 };
75
7f910306 76 PVE::Tools::run_command($cmdstr, %param, logfunc => $logfunc);
aaeeeebe
DM
77}
78
79sub storage_info {
80 my $storage = shift;
81
4a4051d8
DM
82 my $cfg = cfs_read_file('storage.cfg');
83 my $scfg = PVE::Storage::storage_config($cfg, $storage);
aaeeeebe
DM
84 my $type = $scfg->{type};
85
86 die "can't use storage type '$type' for backup\n"
87 if (!($type eq 'dir' || $type eq 'nfs'));
88 die "can't use storage for backups - wrong content type\n"
89 if (!$scfg->{content}->{backup});
90
4a4051d8 91 PVE::Storage::activate_storage($cfg, $storage);
aaeeeebe
DM
92
93 return {
30edfad9 94 dumpdir => PVE::Storage::get_backup_dir($cfg, $storage),
19d5c0f2 95 maxfiles => $scfg->{maxfiles},
aaeeeebe
DM
96 };
97}
98
99sub format_size {
100 my $size = shift;
101
102 my $kb = $size / 1024;
103
104 if ($kb < 1024) {
105 return int ($kb) . "KB";
106 }
107
108 my $mb = $size / (1024*1024);
109
110 if ($mb < 1024) {
111 return int ($mb) . "MB";
112 } else {
113 my $gb = $mb / 1024;
114 return sprintf ("%.2fGB", $gb);
115 }
116}
117
118sub format_time {
119 my $seconds = shift;
120
121 my $hours = int ($seconds/3600);
122 $seconds = $seconds - $hours*3600;
123 my $min = int ($seconds/60);
124 $seconds = $seconds - $min*60;
125
126 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
127}
128
129sub encode8bit {
130 my ($str) = @_;
131
132 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
133
134 return $str;
135}
136
137sub escape_html {
138 my ($str) = @_;
139
140 $str =~ s/&/&amp;/g;
141 $str =~ s/</&lt;/g;
142 $str =~ s/>/&gt;/g;
143
144 return $str;
145}
146
147sub check_bin {
148 my ($bin) = @_;
149
150 foreach my $p (split (/:/, $ENV{PATH})) {
151 my $fn = "$p/$bin";
152 if (-x $fn) {
153 return $fn;
154 }
155 }
156
157 die "unable to find command '$bin'\n";
158}
159
160sub check_vmids {
161 my (@vmids) = @_;
162
163 my $res = [];
164 foreach my $vmid (@vmids) {
165 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
166 $vmid = int ($vmid); # remove leading zeros
4a4051d8 167 next if !$vmid;
aaeeeebe
DM
168 push @$res, $vmid;
169 }
170
171 return $res;
172}
173
174
175sub read_vzdump_defaults {
176
177 my $fn = "/etc/vzdump.conf";
178
179 my $res = {
180 bwlimit => 0,
181 ionice => 7,
182 size => 1024,
183 lockwait => 3*60, # 3 hours
184 stopwait => 10, # 10 minutes
185 mode => 'snapshot',
186 maxfiles => 1,
187 };
188
189 my $fh = IO::File->new ("<$fn");
190 return $res if !$fh;
191
192 my $line;
193 while (defined ($line = <$fh>)) {
194 next if $line =~ m/^\s*$/;
195 next if $line =~ m/^\#/;
196
197 if ($line =~ m/tmpdir:\s*(.*\S)\s*$/) {
198 $res->{tmpdir} = $1;
199 } elsif ($line =~ m/dumpdir:\s*(.*\S)\s*$/) {
200 $res->{dumpdir} = $1;
201 } elsif ($line =~ m/storage:\s*(\S+)\s*$/) {
202 $res->{storage} = $1;
203 } elsif ($line =~ m/script:\s*(.*\S)\s*$/) {
204 $res->{script} = $1;
205 } elsif ($line =~ m/bwlimit:\s*(\d+)\s*$/) {
206 $res->{bwlimit} = int($1);
207 } elsif ($line =~ m/ionice:\s*([0-8])\s*$/) {
208 $res->{ionice} = int($1);
209 } elsif ($line =~ m/lockwait:\s*(\d+)\s*$/) {
210 $res->{lockwait} = int($1);
211 } elsif ($line =~ m/stopwait:\s*(\d+)\s*$/) {
212 $res->{stopwait} = int($1);
213 } elsif ($line =~ m/size:\s*(\d+)\s*$/) {
214 $res->{size} = int($1);
215 } elsif ($line =~ m/maxfiles:\s*(\d+)\s*$/) {
216 $res->{maxfiles} = int($1);
f4a8bab4
DM
217 } elsif ($line =~ m/exclude-path:\s*(.*)\s*$/) {
218 $res->{'exclude-path'} = PVE::Tools::split_args($1);
aaeeeebe
DM
219 } elsif ($line =~ m/mode:\s*(stop|snapshot|suspend)\s*$/) {
220 $res->{mode} = $1;
221 } else {
222 debugmsg ('warn', "unable to parse configuration file '$fn' - error at line " . $., undef, 1);
223 }
224
225 }
226 close ($fh);
227
228 return $res;
229}
230
231
232sub find_add_exclude {
233 my ($self, $excltype, $value) = @_;
234
235 if (($excltype eq '-regex') || ($excltype eq '-files')) {
236 $value = "\.$value";
237 }
238
239 if ($excltype eq '-files') {
240 push @{$self->{findexcl}}, "'('", '-not', '-type', 'd', '-regex' , "'$value'", "')'", '-o';
241 } else {
242 push @{$self->{findexcl}}, "'('", $excltype , "'$value'", '-prune', "')'", '-o';
243 }
244}
245
aaeeeebe
DM
246my $sendmail = sub {
247 my ($self, $tasklist, $totaltime) = @_;
248
249 my $opts = $self->{opts};
250
251 my $mailto = $opts->{mailto};
252
4a4051d8 253 return if !($mailto && scalar(@$mailto));
aaeeeebe
DM
254
255 my $cmdline = $self->{cmdline};
256
257 my $ecount = 0;
258 foreach my $task (@$tasklist) {
259 $ecount++ if $task->{state} ne 'ok';
260 chomp $task->{msg} if $task->{msg};
261 $task->{backuptime} = 0 if !$task->{backuptime};
262 $task->{size} = 0 if !$task->{size};
263 $task->{tarfile} = 'unknown' if !$task->{tarfile};
264 $task->{hostname} = "VM $task->{vmid}" if !$task->{hostname};
265
266 if ($task->{state} eq 'todo') {
267 $task->{msg} = 'aborted';
268 }
269 }
270
271 my $stat = $ecount ? 'backup failed' : 'backup successful';
272
4a4051d8 273 my $hostname = `hostname -f` || PVE::INotify::nodename();
aaeeeebe
DM
274 chomp $hostname;
275
aaeeeebe
DM
276 my $boundary = "----_=_NextPart_001_".int(time).$$;
277
278 my $rcvrarg = '';
279 foreach my $r (@$mailto) {
280 $rcvrarg .= " '$r'";
281 }
282
283 open (MAIL,"|sendmail -B 8BITMIME $rcvrarg") ||
284 die "unable to open 'sendmail' - $!";
285
286 my $rcvrtxt = join (', ', @$mailto);
287
288 print MAIL "Content-Type: multipart/alternative;\n";
289 print MAIL "\tboundary=\"$boundary\"\n";
290 print MAIL "FROM: vzdump backup tool <root>\n";
291 print MAIL "TO: $rcvrtxt\n";
292 print MAIL "SUBJECT: vzdump backup status ($hostname) : $stat\n";
293 print MAIL "\n";
294 print MAIL "This is a multi-part message in MIME format.\n\n";
295 print MAIL "--$boundary\n";
296
297 print MAIL "Content-Type: text/plain;\n";
298 print MAIL "\tcharset=\"UTF8\"\n";
299 print MAIL "Content-Transfer-Encoding: 8bit\n";
300 print MAIL "\n";
301
302 # text part
303
304 my $fill = ' '; # Avoid The Remove Extra Line Breaks Issue (MS Outlook)
305
306 print MAIL sprintf ("${fill}%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
307 foreach my $task (@$tasklist) {
308 my $vmid = $task->{vmid};
309 if ($task->{state} eq 'ok') {
310
311 print MAIL sprintf ("${fill}%-10s %-6s %10s %10s %s\n", $vmid,
312 $task->{state},
313 format_time($task->{backuptime}),
314 format_size ($task->{size}),
315 $task->{tarfile});
316 } else {
317 print MAIL sprintf ("${fill}%-10s %-6s %10s %8.2fMB %s\n", $vmid,
318 $task->{state},
319 format_time($task->{backuptime}),
320 0, '-');
321 }
322 }
323 print MAIL "${fill}\n";
324 print MAIL "${fill}Detailed backup logs:\n";
325 print MAIL "${fill}\n";
326 print MAIL "$fill$cmdline\n";
327 print MAIL "${fill}\n";
328
329 foreach my $task (@$tasklist) {
330 my $vmid = $task->{vmid};
331 my $log = $task->{tmplog};
332 if (!$log) {
333 print MAIL "${fill}$vmid: no log available\n\n";
334 next;
335 }
336 open (TMP, "$log");
337 while (my $line = <TMP>) { print MAIL encode8bit ("${fill}$vmid: $line"); }
338 close (TMP);
339 print MAIL "${fill}\n";
340 }
341
342 # end text part
343 print MAIL "\n--$boundary\n";
344
345 print MAIL "Content-Type: text/html;\n";
346 print MAIL "\tcharset=\"UTF8\"\n";
347 print MAIL "Content-Transfer-Encoding: 8bit\n";
348 print MAIL "\n";
349
350 # html part
351
352 print MAIL "<html><body>\n";
353
354 print MAIL "<table border=1 cellpadding=3>\n";
355
356 print MAIL "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
357
358 my $ssize = 0;
359
360 foreach my $task (@$tasklist) {
361 my $vmid = $task->{vmid};
362 my $name = $task->{hostname};
363
364 if ($task->{state} eq 'ok') {
365
366 $ssize += $task->{size};
367
368 print MAIL sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
369 $vmid, $name,
370 format_time($task->{backuptime}),
371 format_size ($task->{size}),
372 escape_html ($task->{tarfile}));
373 } else {
374 print MAIL sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
375
376 $vmid, $name, format_time($task->{backuptime}),
377 escape_html ($task->{msg}));
378 }
379 }
380
381 print MAIL sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
382 format_time ($totaltime), format_size ($ssize));
383
384 print MAIL "</table><br><br>\n";
385 print MAIL "Detailed backup logs:<br>\n";
386 print MAIL "<br>\n";
387 print MAIL "<pre>\n";
388 print MAIL escape_html($cmdline) . "\n";
389 print MAIL "\n";
390
391 foreach my $task (@$tasklist) {
392 my $vmid = $task->{vmid};
393 my $log = $task->{tmplog};
394 if (!$log) {
395 print MAIL "$vmid: no log available\n\n";
396 next;
397 }
398 open (TMP, "$log");
399 while (my $line = <TMP>) {
400 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
401 print MAIL encode8bit ("$vmid: <font color=red>".
402 escape_html ($line) . "</font>");
403 } else {
404 print MAIL encode8bit ("$vmid: " . escape_html ($line));
405 }
406 }
407 close (TMP);
408 print MAIL "\n";
409 }
410 print MAIL "</pre>\n";
411
412 print MAIL "</body></html>\n";
413
414 # end html part
415 print MAIL "\n--$boundary--\n";
416
4a4051d8 417 close(MAIL);
aaeeeebe
DM
418};
419
420sub new {
a7e42354 421 my ($class, $cmdline, $opts, $skiplist) = @_;
aaeeeebe
DM
422
423 mkpath $logdir;
424
425 check_bin ('cp');
426 check_bin ('df');
427 check_bin ('sendmail');
428 check_bin ('rsync');
429 check_bin ('tar');
430 check_bin ('mount');
431 check_bin ('umount');
432 check_bin ('cstream');
433 check_bin ('ionice');
434
47664cbe 435 if ($opts->{mode} && $opts->{mode} eq 'snapshot') {
aaeeeebe
DM
436 check_bin ('lvcreate');
437 check_bin ('lvs');
438 check_bin ('lvremove');
439 }
440
441 my $defaults = read_vzdump_defaults();
442
899b8373
DM
443 my $maxfiles = $opts->{maxfiles};
444 $opts->{remove} = 1 if !defined($opts->{remove});
445
aaeeeebe
DM
446 foreach my $k (keys %$defaults) {
447 if ($k eq 'dumpdir' || $k eq 'storage') {
448 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
449 !defined ($opts->{storage});
450 } else {
451 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
452 }
453 }
454
aaeeeebe
DM
455 $opts->{dumpdir} =~ s|/+$|| if ($opts->{dumpdir});
456 $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
457
a7e42354
DM
458 $skiplist = [] if !$skiplist;
459 my $self = bless { cmdline => $cmdline, opts => $opts, skiplist => $skiplist };
aaeeeebe
DM
460
461 #always skip '.'
462 push @{$self->{findexcl}}, "'('", '-regex' , "'^\\.\$'", "')'", '-o';
463
464 $self->find_add_exclude ('-type', 's'); # skip sockets
465
f4a8bab4
DM
466 if ($defaults->{'exclude-path'}) {
467 foreach my $path (@{$defaults->{'exclude-path'}}) {
468 $self->find_add_exclude ('-regex', $path);
469 }
470 }
471
aaeeeebe
DM
472 if ($opts->{'exclude-path'}) {
473 foreach my $path (@{$opts->{'exclude-path'}}) {
474 $self->find_add_exclude ('-regex', $path);
475 }
476 }
477
478 if ($opts->{stdexcludes}) {
479 $self->find_add_exclude ('-files', '/var/log/.+');
480 $self->find_add_exclude ('-regex', '/tmp/.+');
481 $self->find_add_exclude ('-regex', '/var/tmp/.+');
482 $self->find_add_exclude ('-regex', '/var/run/.+pid');
483 }
484
485 foreach my $p (@plugins) {
486
487 my $pd = $p->new ($self);
488
489 push @{$self->{plugins}}, $pd;
aaeeeebe
DM
490 }
491
492 if (!$opts->{dumpdir} && !$opts->{storage}) {
19d5c0f2 493 $opts->{storage} = 'local';
aaeeeebe
DM
494 }
495
496 if ($opts->{storage}) {
497 my $info = storage_info ($opts->{storage});
498 $opts->{dumpdir} = $info->{dumpdir};
899b8373 499 $maxfiles = $info->{maxfiles} if !$maxfiles && $info->{maxfiles};
aaeeeebe
DM
500 } elsif ($opts->{dumpdir}) {
501 die "dumpdir '$opts->{dumpdir}' does not exist\n"
502 if ! -d $opts->{dumpdir};
503 } else {
504 die "internal error";
505 }
506
507 if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
508 die "tmpdir '$opts->{tmpdir}' does not exist\n";
509 }
510
899b8373
DM
511 $opts->{maxfiles} = $maxfiles if $maxfiles;
512
aaeeeebe
DM
513 return $self;
514
515}
516
517sub get_lvm_mapping {
518
519 my $devmapper;
520
d93d0459
DM
521 my $cmd = ['lvs', '--units', 'm', '--separator', ':', '--noheadings',
522 '-o', 'vg_name,lv_name,lv_size' ];
523
524 my $parser = sub {
525 my $line = shift;
526 if ($line =~ m|^\s*(\S+):(\S+):(\d+(\.\d+))[Mm]$|) {
527 my $vg = $1;
528 my $lv = $2;
529 $devmapper->{"/dev/$vg/$lv"} = [$vg, $lv];
530 my $qlv = $lv;
531 $qlv =~ s/-/--/g;
532 my $qvg = $vg;
533 $qvg =~ s/-/--/g;
534 $devmapper->{"/dev/mapper/$qvg-$qlv"} = [$vg, $lv];
535 }
536 };
537
538 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
539 warn $@ if $@;
aaeeeebe
DM
540
541 return $devmapper;
542}
543
544sub get_mount_info {
545 my ($dir) = @_;
546
d93d0459 547 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
aaeeeebe 548
d93d0459 549 my $res;
aaeeeebe 550
d93d0459
DM
551 my $parser = sub {
552 my $line = shift;
553 if (my ($fsid, $fstype, $mp) = $line =~
554 m|^(\S+.*)\s+(\S+)\s+\d+\s+\d+\s+\d+\s+\d+%\s+(/.*)$|) {
555 $res = {
556 device => $fsid,
557 fstype => $fstype,
558 mountpoint => $mp,
559 };
560 }
aaeeeebe 561 };
d93d0459
DM
562
563 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
564 warn $@ if $@;
565
566 return $res;
aaeeeebe
DM
567}
568
569sub get_lvm_device {
570 my ($dir, $mapping) = @_;
571
5dc86eb8 572 my $info = get_mount_info($dir);
aaeeeebe
DM
573
574 return undef if !$info;
575
576 my $dev = $info->{device};
577
578 my ($vg, $lv);
579
580 ($vg, $lv) = @{$mapping->{$dev}} if defined $mapping->{$dev};
581
582 return wantarray ? ($dev, $info->{mountpoint}, $vg, $lv, $info->{fstype}) : $dev;
583}
584
585sub getlock {
586 my ($self) = @_;
587
588 my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
589
590 if (!open (SERVER_FLCK, ">>$lockfile")) {
591 debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
592 exit (-1);
593 }
594
595 if (flock (SERVER_FLCK, LOCK_EX|LOCK_NB)) {
596 return;
597 }
598
599 if (!$maxwait) {
600 debugmsg ('err', "can't aquire lock '$lockfile' (wait = 0)", undef, 1);
601 exit (-1);
602 }
603
604 debugmsg('info', "trying to get global lock - waiting...", undef, 1);
605
606 eval {
607 alarm ($maxwait * 60);
608
609 local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
610
611 if (!flock (SERVER_FLCK, LOCK_EX)) {
612 my $err = $!;
613 close (SERVER_FLCK);
614 alarm (0);
615 die "$err\n";
616 }
617 alarm (0);
618 };
619 alarm (0);
620
621 my $err = $@;
622
623 if ($err) {
624 debugmsg ('err', "can't aquire lock '$lockfile' - $err", undef, 1);
625 exit (-1);
626 }
627
628 debugmsg('info', "got global lock", undef, 1);
629}
630
631sub run_hook_script {
632 my ($self, $phase, $task, $logfd) = @_;
633
634 my $opts = $self->{opts};
635
636 my $script = $opts->{script};
637
638 return if !$script;
639
640 my $cmd = "$script $phase";
641
642 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
643
644 local %ENV;
645
646 foreach my $ek (qw(vmtype dumpdir hostname tarfile logfile)) {
647 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
648 }
649
650 run_command ($logfd, $cmd);
651}
652
d7550e09
DM
653sub compressor_info {
654 my ($opt_compress) = @_;
655
656 if (!$opt_compress || $opt_compress eq '0') {
657 return undef;
658 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
659 return ('lzop', 'lzo');
660 } elsif ($opt_compress eq 'gzip') {
661 return ('gzip', 'gz');
662 } else {
663 die "internal error - unknown compression option '$opt_compress'";
664 }
665}
899b8373
DM
666
667sub get_backup_file_list {
668 my ($dir, $bkname, $exclude_fn) = @_;
669
670 my $bklist = [];
671 foreach my $fn (<$dir/${bkname}-*>) {
672 next if $exclude_fn && $fn eq $exclude_fn;
673 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?)))$!) {
674 $fn = "$dir/$1"; # untaint
675 my $t = timelocal ($7, $6, $5, $4, $3 - 1, $2 - 1900);
676 push @$bklist, [$fn, $t];
677 }
678 }
679
680 return $bklist;
681}
d7550e09 682
aaeeeebe
DM
683sub exec_backup_task {
684 my ($self, $task) = @_;
685
686 my $opts = $self->{opts};
687
688 my $vmid = $task->{vmid};
689 my $plugin = $task->{plugin};
690
691 my $vmstarttime = time ();
692
693 my $logfd;
694
695 my $cleanup = {};
696
697 my $vmstoptime = 0;
698
699 eval {
700 die "unable to find VM '$vmid'\n" if !$plugin;
701
702 my $vmtype = $plugin->type();
703
704 my $tmplog = "$logdir/$vmtype-$vmid.log";
705
706 my $lt = localtime();
707
708 my $bkname = "vzdump-$vmtype-$vmid";
709 my $basename = sprintf "${bkname}-%04d_%02d_%02d-%02d_%02d_%02d",
710 $lt->year + 1900, $lt->mon + 1, $lt->mday,
711 $lt->hour, $lt->min, $lt->sec;
712
899b8373
DM
713 my $maxfiles = $opts->{maxfiles};
714
715 if ($maxfiles && !$opts->{remove}) {
716 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
717 die "only $maxfiles backup(s) allowed - please consider to remove old backup files.\n"
718 if scalar(@$bklist) >= $maxfiles;
719 }
720
aaeeeebe
DM
721 my $logfile = $task->{logfile} = "$opts->{dumpdir}/$basename.log";
722
d7550e09
DM
723 my $ext = '.tar';
724 my ($comp, $comp_ext) = compressor_info($opts->{compress});
725 if ($comp && $comp_ext) {
726 $ext .= ".${comp_ext}";
727 }
aaeeeebe
DM
728
729 if ($opts->{stdout}) {
730 $task->{tarfile} = '-';
731 } else {
732 my $tarfile = $task->{tarfile} = "$opts->{dumpdir}/$basename$ext";
733 $task->{tmptar} = $task->{tarfile};
734 $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
735 unlink $task->{tmptar};
736 }
737
738 $task->{vmtype} = $vmtype;
739
740 if ($opts->{tmpdir}) {
741 $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp$$";
742 } else {
743 # dumpdir is posix? then use it as temporary dir
5dc86eb8 744 my $info = get_mount_info($opts->{dumpdir});
aaeeeebe
DM
745 if ($vmtype eq 'qemu' ||
746 grep ($_ eq $info->{fstype}, @posix_filesystems)) {
747 $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
748 } else {
749 $task->{tmpdir} = "/var/tmp/vzdumptmp$$";
750 debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
751 "using $task->{tmpdir} for temporary files", $logfd);
752 }
753 }
754
755 rmtree $task->{tmpdir};
756 mkdir $task->{tmpdir};
757 -d $task->{tmpdir} ||
758 die "unable to create temporary directory '$task->{tmpdir}'";
759
760 $logfd = IO::File->new (">$tmplog") ||
761 die "unable to create log file '$tmplog'";
762
763 $task->{dumpdir} = $opts->{dumpdir};
764
765 $task->{tmplog} = $tmplog;
766
767 unlink $logfile;
768
769 debugmsg ('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
770
771 $plugin->set_logfd ($logfd);
772
773 # test is VM is running
774 my ($running, $status_text) = $plugin->vm_status ($vmid);
775
776 debugmsg ('info', "status = ${status_text}", $logfd);
777
778 # lock VM (prevent config changes)
779 $plugin->lock_vm ($vmid);
780
781 $cleanup->{unlock} = 1;
782
783 # prepare
784
785 my $mode = $running ? $opts->{mode} : 'stop';
786
787 if ($mode eq 'snapshot') {
788 my %saved_task = %$task;
789 eval { $plugin->prepare ($task, $vmid, $mode); };
790 if (my $err = $@) {
791 die $err if $err !~ m/^mode failure/;
792 debugmsg ('info', $err, $logfd);
793 debugmsg ('info', "trying 'suspend' mode instead", $logfd);
794 $mode = 'suspend'; # so prepare is called again below
795 %$task = %saved_task;
796 }
797 }
798
799 $task->{mode} = $mode;
800
801 debugmsg ('info', "backup mode: $mode", $logfd);
802
803 debugmsg ('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
804 if $opts->{bwlimit};
805
806 debugmsg ('info', "ionice priority: $opts->{ionice}", $logfd);
807
808 if ($mode eq 'stop') {
809
810 $plugin->prepare ($task, $vmid, $mode);
811
812 $self->run_hook_script ('backup-start', $task, $logfd);
813
814 if ($running) {
815 debugmsg ('info', "stopping vm", $logfd);
816 $vmstoptime = time ();
817 $self->run_hook_script ('pre-stop', $task, $logfd);
818 $plugin->stop_vm ($task, $vmid);
819 $cleanup->{restart} = 1;
820 }
821
822
823 } elsif ($mode eq 'suspend') {
824
825 $plugin->prepare ($task, $vmid, $mode);
826
827 $self->run_hook_script ('backup-start', $task, $logfd);
828
829 if ($vmtype eq 'openvz') {
830 # pre-suspend rsync
831 $plugin->copy_data_phase1 ($task, $vmid);
832 }
833
834 debugmsg ('info', "suspend vm", $logfd);
835 $vmstoptime = time ();
836 $self->run_hook_script ('pre-stop', $task, $logfd);
837 $plugin->suspend_vm ($task, $vmid);
838 $cleanup->{resume} = 1;
839
840 if ($vmtype eq 'openvz') {
841 # post-suspend rsync
842 $plugin->copy_data_phase2 ($task, $vmid);
843
844 debugmsg ('info', "resume vm", $logfd);
845 $cleanup->{resume} = 0;
846 $self->run_hook_script ('pre-restart', $task, $logfd);
847 $plugin->resume_vm ($task, $vmid);
848 my $delay = time () - $vmstoptime;
849 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
850 }
851
852 } elsif ($mode eq 'snapshot') {
853
854 my $snapshot_count = $task->{snapshot_count} || 0;
855
856 $self->run_hook_script ('pre-stop', $task, $logfd);
857
858 if ($snapshot_count > 1) {
859 debugmsg ('info', "suspend vm to make snapshot", $logfd);
860 $vmstoptime = time ();
861 $plugin->suspend_vm ($task, $vmid);
862 $cleanup->{resume} = 1;
863 }
864
865 $plugin->snapshot ($task, $vmid);
866
867 $self->run_hook_script ('pre-restart', $task, $logfd);
868
869 if ($snapshot_count > 1) {
870 debugmsg ('info', "resume vm", $logfd);
871 $cleanup->{resume} = 0;
872 $plugin->resume_vm ($task, $vmid);
873 my $delay = time () - $vmstoptime;
874 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
875 }
876
877 } else {
878 die "internal error - unknown mode '$mode'\n";
879 }
880
881 # assemble archive image
882 $plugin->assemble ($task, $vmid);
883
884 # produce archive
885
886 if ($opts->{stdout}) {
887 debugmsg ('info', "sending archive to stdout", $logfd);
d7550e09 888 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
889 $self->run_hook_script ('backup-end', $task, $logfd);
890 return;
891 }
892
893 debugmsg ('info', "creating archive '$task->{tarfile}'", $logfd);
d7550e09 894 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
895
896 rename ($task->{tmptar}, $task->{tarfile}) ||
897 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
898
899 # determine size
900 $task->{size} = (-s $task->{tarfile}) || 0;
901 my $cs = format_size ($task->{size});
902 debugmsg ('info', "archive file size: $cs", $logfd);
903
904 # purge older backup
905
899b8373
DM
906 if ($maxfiles && $opts->{remove}) {
907 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname, $task->{tarfile});
908 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
aaeeeebe 909
899b8373
DM
910 while (scalar (@$bklist) >= $maxfiles) {
911 my $d = pop @$bklist;
aaeeeebe
DM
912 debugmsg ('info', "delete old backup '$d->[0]'", $logfd);
913 unlink $d->[0];
914 my $logfn = $d->[0];
d7550e09 915 $logfn =~ s/\.(tgz|(tar(\.(gz|lzo))?))$/\.log/;
aaeeeebe
DM
916 unlink $logfn;
917 }
918 }
919
920 $self->run_hook_script ('backup-end', $task, $logfd);
921 };
922 my $err = $@;
923
924 if ($plugin) {
925 # clean-up
926
927 if ($cleanup->{unlock}) {
928 eval { $plugin->unlock_vm ($vmid); };
929 warn $@ if $@;
930 }
931
932 eval { $plugin->cleanup ($task, $vmid) };
933 warn $@ if $@;
934
935 eval { $plugin->set_logfd (undef); };
936 warn $@ if $@;
937
938 if ($cleanup->{resume} || $cleanup->{restart}) {
939 eval {
940 $self->run_hook_script ('pre-restart', $task, $logfd);
941 if ($cleanup->{resume}) {
942 debugmsg ('info', "resume vm", $logfd);
943 $plugin->resume_vm ($task, $vmid);
944 } else {
945 debugmsg ('info', "restarting vm", $logfd);
946 $plugin->start_vm ($task, $vmid);
947 }
948 };
949 my $err = $@;
950 if ($err) {
951 warn $err;
952 } else {
953 my $delay = time () - $vmstoptime;
954 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
955 }
956 }
957 }
958
959 eval { unlink $task->{tmptar} if $task->{tmptar} && -f $task->{tmptar}; };
960 warn $@ if $@;
961
962 eval { rmtree $task->{tmpdir} if $task->{tmpdir} && -d $task->{tmpdir}; };
963 warn $@ if $@;
964
965 my $delay = $task->{backuptime} = time () - $vmstarttime;
966
967 if ($err) {
968 $task->{state} = 'err';
969 $task->{msg} = $err;
970 debugmsg ('err', "Backup of VM $vmid failed - $err", $logfd, 1);
971
972 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
973
974 } else {
975 $task->{state} = 'ok';
976 my $tstr = format_time ($delay);
977 debugmsg ('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
978 }
979
980 close ($logfd) if $logfd;
981
982 if ($task->{tmplog} && $task->{logfile}) {
983 system ("cp '$task->{tmplog}' '$task->{logfile}'");
984 }
985
986 eval { $self->run_hook_script ('log-end', $task); };
987
988 die $err if $err && $err =~ m/^interrupted by signal$/;
989}
990
991sub exec_backup {
d7550e09 992 my ($self, $rpcenv, $authuser) = @_;
aaeeeebe
DM
993
994 my $opts = $self->{opts};
995
996 debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
a7e42354
DM
997 debugmsg ('info', "skip external VMs: " . join(', ', @{$self->{skiplist}}))
998 if scalar(@{$self->{skiplist}});
999
aaeeeebe
DM
1000 my $tasklist = [];
1001
1002 if ($opts->{all}) {
1003 foreach my $plugin (@{$self->{plugins}}) {
1004 my $vmlist = $plugin->vmlist();
1005 foreach my $vmid (sort @$vmlist) {
1006 next if grep { $_ eq $vmid } @{$opts->{exclude}};
98e84b16 1007 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
aaeeeebe
DM
1008 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin };
1009 }
1010 }
1011 } else {
1012 foreach my $vmid (sort @{$opts->{vmids}}) {
1013 my $plugin;
1014 foreach my $pg (@{$self->{plugins}}) {
1015 my $vmlist = $pg->vmlist();
1016 if (grep { $_ eq $vmid } @$vmlist) {
1017 $plugin = $pg;
1018 last;
1019 }
1020 }
98e84b16 1021 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
aaeeeebe
DM
1022 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin };
1023 }
1024 }
1025
1026 my $starttime = time();
1027 my $errcount = 0;
1028 eval {
1029
1030 $self->run_hook_script ('job-start');
1031
1032 foreach my $task (@$tasklist) {
1033 $self->exec_backup_task ($task);
1034 $errcount += 1 if $task->{state} ne 'ok';
1035 }
1036
1037 $self->run_hook_script ('job-end');
1038 };
1039 my $err = $@;
1040
1041 $self->run_hook_script ('job-abort') if $err;
1042
1043 if ($err) {
1044 debugmsg ('err', "Backup job failed - $err", undef, 1);
1045 } else {
1046 if ($errcount) {
1047 debugmsg ('info', "Backup job finished with errors", undef, 1);
1048 } else {
61ca4432 1049 debugmsg ('info', "Backup job finished successfully", undef, 1);
aaeeeebe
DM
1050 }
1051 }
1052
1053 my $totaltime = time() - $starttime;
1054
1055 eval { $self->$sendmail ($tasklist, $totaltime); };
1056 debugmsg ('err', $@) if $@;
4a4051d8
DM
1057
1058 die $err if $err;
1059
1060 die "job errors\n" if $errcount;
aaeeeebe
DM
1061}
1062
ac27b58d
DM
1063my $confdesc = {
1064 vmid => {
1065 type => 'string', format => 'pve-vmid-list',
1066 description => "The ID of the VM you want to backup.",
1067 optional => 1,
1068 },
1069 node => get_standard_option('pve-node', {
1070 description => "Only run if executed on this node.",
1071 optional => 1,
1072 }),
1073 all => {
1074 type => 'boolean',
1075 description => "Backup all known VMs on this host.",
1076 optional => 1,
1077 default => 0,
1078 },
1079 stdexcludes => {
1080 type => 'boolean',
1081 description => "Exclude temorary files and logs.",
1082 optional => 1,
1083 default => 1,
1084 },
1085 compress => {
d7550e09
DM
1086 type => 'string',
1087 description => "Compress dump file.",
ac27b58d 1088 optional => 1,
d7550e09
DM
1089 enum => ['0', '1', 'gzip', 'lzo'],
1090 default => 'lzo',
ac27b58d
DM
1091 },
1092 quiet => {
1093 type => 'boolean',
1094 description => "Be quiet.",
1095 optional => 1,
1096 default => 0,
1097 },
47664cbe
DM
1098 mode => {
1099 type => 'string',
1100 description => "Backup mode.",
ac27b58d 1101 optional => 1,
47664cbe
DM
1102 default => 'stop',
1103 enum => [ 'snapshot', 'suspend', 'stop' ],
ac27b58d
DM
1104 },
1105 exclude => {
1106 type => 'string', format => 'pve-vmid-list',
1107 description => "exclude specified VMs (assumes --all)",
1108 optional => 1,
1109 },
1110 'exclude-path' => {
1111 type => 'string', format => 'string-alist',
1112 description => "exclude certain files/directories (regex).",
1113 optional => 1,
1114 },
1115 mailto => {
1116 type => 'string', format => 'string-list',
1117 description => "",
1118 optional => 1,
1119 },
1120 tmpdir => {
1121 type => 'string',
1122 description => "Store temporary files to specified directory.",
1123 optional => 1,
1124 },
1125 dumpdir => {
1126 type => 'string',
1127 description => "Store resulting files to specified directory.",
1128 optional => 1,
1129 },
1130 script => {
1131 type => 'string',
1132 description => "Use specified hook script.",
1133 optional => 1,
1134 },
1135 storage => get_standard_option('pve-storage-id', {
1136 description => "Store resulting file to this storage.",
1137 optional => 1,
1138 }),
1139 size => {
1140 type => 'integer',
1141 description => "LVM snapshot size im MB.",
1142 optional => 1,
1143 minimum => 500,
1144 },
1145 bwlimit => {
1146 type => 'integer',
1147 description => "Limit I/O bandwidth (KBytes per second).",
1148 optional => 1,
1149 minimum => 0,
1150 },
1151 ionice => {
1152 type => 'integer',
1153 description => "Set CFQ ionice priority.",
1154 optional => 1,
1155 minimum => 0,
1156 maximum => 8,
1157 },
1158 lockwait => {
1159 type => 'integer',
1160 description => "Maximal time to wait for the global lock (minutes).",
1161 optional => 1,
1162 minimum => 0,
1163 },
1164 stopwait => {
1165 type => 'integer',
1166 description => "Maximal time to wait until a VM is stopped (minutes).",
1167 optional => 1,
1168 minimum => 0,
1169 },
1170 maxfiles => {
1171 type => 'integer',
1172 description => "Maximal number of backup files per VM.",
1173 optional => 1,
1174 minimum => 1,
1175 },
899b8373
DM
1176 remove => {
1177 type => 'boolean',
1178 description => "Remove old backup files if there are more than 'maxfiles' backup files.",
1179 optional => 1,
1180 default => 1,
1181 },
ac27b58d
DM
1182};
1183
47664cbe
DM
1184sub option_exists {
1185 my $key = shift;
1186 return defined($confdesc->{$key});
1187}
1188
ac27b58d
DM
1189# add JSON properties for create and set function
1190sub json_config_properties {
1191 my $prop = shift;
1192
1193 foreach my $opt (keys %$confdesc) {
1194 $prop->{$opt} = $confdesc->{$opt};
1195 }
1196
1197 return $prop;
1198}
1199
31aef761
DM
1200sub verify_vzdump_parameters {
1201 my ($param, $check_missing) = @_;
1202
1203 raise_param_exc({ all => "option conflicts with option 'vmid'"})
1204 if $param->{all} && $param->{vmid};
1205
1206 raise_param_exc({ exclude => "option conflicts with option 'vmid'"})
1207 if $param->{exclude} && $param->{vmid};
1208
1209 $param->{all} = 1 if defined($param->{exclude});
1210
1211 return if !$check_missing;
1212
1213 raise_param_exc({ vmid => "property is missing"})
1214 if !$param->{all} && !$param->{vmid};
1215
1216}
1217
1218sub command_line {
1219 my ($param) = @_;
1220
1221 my $cmd = "vzdump";
1222
1223 if ($param->{vmid}) {
1224 $cmd .= " " . join(' ', PVE::Tools::split_list($param->{vmid}));
1225 }
1226
1227 foreach my $p (keys %$param) {
1228 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' || $p eq 'dow';
1229 my $v = $param->{$p};
1230 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
f4a8bab4
DM
1231 if ($p eq 'exclude-path') {
1232 foreach my $path (split(/\0/, $v || '')) {
1233 $cmd .= " --$p " . PVE::Tools::shellquote($path);
1234 }
1235 } else {
1236 $cmd .= " --$p " . PVE::Tools::shellquote($v) if defined($v) && $v ne '';
1237 }
31aef761
DM
1238 }
1239
1240 return $cmd;
1241}
1242
aaeeeebe 12431;