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