11 use POSIX
qw(strftime);
14 use PVE
::Cluster
qw(cfs_read_file);
15 use PVE
::DataCenterConfig
;
16 use PVE
::Exception
qw(raise_param_exc);
18 use PVE
::HA
::Env
::PVE2
;
19 use PVE
::JSONSchema
qw(get_standard_option);
20 use PVE
::RPCEnvironment
;
22 use PVE
::VZDump
::Common
;
23 use PVE
::VZDump
::Plugin
;
24 use PVE
::Tools
qw(extract_param split_list);
27 my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
29 my $lockfile = '/var/run/vzdump.lock';
30 my $pidfile = '/var/run/vzdump.pid';
31 my $logdir = '/var/log/vzdump';
35 my $confdesc = PVE
::VZDump
::Common
::get_confdesc
();
37 # Load available plugins
38 my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
39 foreach my $plug (@pve_vzdump_classes) {
40 my $filename = "/usr/share/perl5/$plug.pm";
41 $filename =~ s!::!/!g;
43 eval { require $filename; };
56 my ($mtype, $msg, $logfd, $syslog) = @_;
58 PVE
::VZDump
::Plugin
::debugmsg
(@_);
62 my ($logfd, $cmdstr, %param) = @_;
66 debugmsg
('info', $line, $logfd);
69 PVE
::Tools
::run_command
($cmdstr, %param, logfunc
=> $logfunc);
75 my $cfg = PVE
::Storage
::config
();
76 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
77 my $type = $scfg->{type
};
79 die "can't use storage type '$type' for backup\n"
80 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'
81 || $type eq 'cifs' || $type eq 'cephfs' || $type eq 'pbs'));
82 die "can't use storage '$storage' for backups - wrong content type\n"
83 if (!$scfg->{content
}->{backup
});
85 PVE
::Storage
::activate_storage
($cfg, $storage);
89 maxfiles
=> $scfg->{maxfiles
},
92 $info->{'prune-backups'} = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'})
93 if defined($scfg->{'prune-backups'});
95 die "cannot have 'maxfiles' and 'prune-backups' configured at the same time\n"
96 if defined($info->{'prune-backups'}) && defined($info->{maxfiles
});
101 $info->{dumpdir
} = PVE
::Storage
::get_backup_dir
($cfg, $storage);
110 my $kb = $size / 1024;
113 return int ($kb) . "KB";
116 my $mb = $size / (1024*1024);
118 return int ($mb) . "MB";
122 return sprintf ("%.2fGB", $gb);
125 return sprintf ("%.2fTB", $tb);
131 my $hours = int ($seconds/3600);
132 $seconds = $seconds - $hours*3600;
133 my $min = int ($seconds/60);
134 $seconds = $seconds - $min*60;
136 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
142 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
160 foreach my $p (split (/:/, $ENV{PATH
})) {
167 die "unable to find command '$bin'\n";
174 for my $vmid (sort {$a <=> $b} @vmids) {
175 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
176 $vmid = int ($vmid); # remove leading zeros
185 sub read_vzdump_defaults
{
187 my $fn = "/etc/vzdump.conf";
191 my $default = $confdesc->{$_}->{default};
192 defined($default) ?
($_ => $default) : ()
197 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
198 return $defaults if $@;
200 my $conf_schema = { type
=> 'object', properties
=> $confdesc, };
201 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
202 if (my $excludes = $res->{'exclude-path'}) {
203 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
205 if (defined($res->{mailto
})) {
206 my @mailto = split_list
($res->{mailto
});
207 $res->{mailto
} = [ @mailto ];
210 foreach my $key (keys %$defaults) {
211 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
217 use constant MAX_MAIL_SIZE
=> 1024*1024;
219 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
221 my $opts = $self->{opts
};
223 my $mailto = $opts->{mailto
};
225 return if !($mailto && scalar(@$mailto));
227 my $cmdline = $self->{cmdline
};
230 foreach my $task (@$tasklist) {
231 $ecount++ if $task->{state} ne 'ok';
232 chomp $task->{msg
} if $task->{msg
};
233 $task->{backuptime
} = 0 if !$task->{backuptime
};
234 $task->{size
} = 0 if !$task->{size
};
235 $task->{target
} = 'unknown' if !$task->{target
};
236 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
238 if ($task->{state} eq 'todo') {
239 $task->{msg
} = 'aborted';
243 my $notify = $opts->{mailnotification
} || 'always';
244 return if (!$ecount && !$err && ($notify eq 'failure'));
246 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
249 $stat .= ": multiple problems";
256 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
260 my $text = $err ?
"$err\n\n" : '';
261 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
262 foreach my $task (@$tasklist) {
263 my $vmid = $task->{vmid
};
264 if ($task->{state} eq 'ok') {
266 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", $vmid,
268 format_time
($task->{backuptime
}),
269 format_size
($task->{size
}),
272 $text .= sprintf ("%-10s %-6s %10s %8.2fMB %s\n", $vmid,
274 format_time
($task->{backuptime
}),
280 $text_log_part .= "\nDetailed backup logs:\n\n";
281 $text_log_part .= "$cmdline\n\n";
283 $text_log_part .= $detail_pre . "\n" if defined($detail_pre);
284 foreach my $task (@$tasklist) {
285 my $vmid = $task->{vmid
};
286 my $log = $task->{tmplog
};
288 $text_log_part .= "$vmid: no log available\n\n";
291 if (open (TMP
, "$log")) {
292 while (my $line = <TMP
>) {
293 next if $line =~ /^status: \d+/; # not useful in mails
294 $text_log_part .= encode8bit
("$vmid: $line");
297 $text_log_part .= "$vmid: Could not open log file\n\n";
300 $text_log_part .= "\n";
302 $text_log_part .= $detail_post if defined($detail_post);
305 my $html = "<html><body>\n";
306 $html .= "<p>" . (escape_html
($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
307 $html .= "<table border=1 cellpadding=3>\n";
308 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
312 foreach my $task (@$tasklist) {
313 my $vmid = $task->{vmid
};
314 my $name = $task->{hostname
};
316 if ($task->{state} eq 'ok') {
318 $ssize += $task->{size
};
320 $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
322 format_time
($task->{backuptime
}),
323 format_size
($task->{size
}),
324 escape_html
($task->{target
}));
326 $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
327 $vmid, $name, format_time
($task->{backuptime
}),
328 escape_html
($task->{msg
}));
332 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
333 format_time
($totaltime), format_size
($ssize));
335 $html .= "\n</table><br><br>\n";
337 $html_log_part .= "Detailed backup logs:<br /><br />\n";
338 $html_log_part .= "<pre>\n";
339 $html_log_part .= escape_html
($cmdline) . "\n\n";
341 $html_log_part .= escape_html
($detail_pre) . "\n" if defined($detail_pre);
342 foreach my $task (@$tasklist) {
343 my $vmid = $task->{vmid
};
344 my $log = $task->{tmplog
};
346 $html_log_part .= "$vmid: no log available\n\n";
349 if (open (TMP
, "$log")) {
350 while (my $line = <TMP
>) {
351 next if $line =~ /^status: \d+/; # not useful in mails
352 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
353 $html_log_part .= encode8bit
("$vmid: <font color=red>".
354 escape_html
($line) . "</font>");
356 $html_log_part .= encode8bit
("$vmid: " . escape_html
($line));
360 $html_log_part .= "$vmid: Could not open log file\n\n";
363 $html_log_part .= "\n";
365 $html_log_part .= escape_html
($detail_post) if defined($detail_post);
366 $html_log_part .= "</pre>";
367 my $html_end .= "\n</body></html>\n";
370 if (length($text) + length($text_log_part) +
371 length($html) + length($html_log_part) < MAX_MAIL_SIZE
)
373 $html .= $html_log_part;
374 $text .= $text_log_part;
376 my $msg = "Log output was too long to be sent by mail. ".
377 "See Task History for details!\n";
379 $html .= "<p>$msg</p>";
383 my $subject = "vzdump backup status ($hostname) : $stat";
385 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
386 my $mailfrom = $dcconf->{email_from
} || "root";
388 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
392 my ($class, $cmdline, $opts, $skiplist) = @_;
398 check_bin
('sendmail');
402 check_bin
('umount');
403 check_bin
('cstream');
404 check_bin
('ionice');
406 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
407 check_bin
('lvcreate');
409 check_bin
('lvremove');
412 my $defaults = read_vzdump_defaults
();
414 $opts->{remove
} = 1 if !defined($opts->{remove
});
416 foreach my $k (keys %$defaults) {
417 next if $k eq 'exclude-path' || $k eq 'maxfiles'; # dealt with separately
418 if ($k eq 'dumpdir' || $k eq 'storage') {
419 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
420 !defined ($opts->{storage
});
422 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
426 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
427 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
429 $skiplist = [] if !$skiplist;
430 my $self = bless { cmdline
=> $cmdline, opts
=> $opts, skiplist
=> $skiplist };
432 my $findexcl = $self->{findexcl
} = [];
433 if ($defaults->{'exclude-path'}) {
434 push @$findexcl, @{$defaults->{'exclude-path'}};
437 if ($opts->{'exclude-path'}) {
438 push @$findexcl, @{$opts->{'exclude-path'}};
441 if ($opts->{stdexcludes
}) {
442 push @$findexcl, '/tmp/?*',
447 foreach my $p (@plugins) {
449 my $pd = $p->new ($self);
451 push @{$self->{plugins
}}, $pd;
454 if (defined($opts->{storage
}) && $opts->{stdout
}) {
455 die "cannot use options 'storage' and 'stdout' at the same time\n";
456 } elsif (defined($opts->{storage
}) && defined($opts->{dumpdir
})) {
457 die "cannot use options 'storage' and 'dumpdir' at the same time\n";
460 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
461 $opts->{storage
} = 'local';
466 if ($opts->{storage
}) {
467 my $info = eval { storage_info
($opts->{storage
}) };
469 $errors .= "could not get storage information for '$opts->{storage}': $err";
471 $opts->{dumpdir
} = $info->{dumpdir
};
472 $opts->{scfg
} = $info->{scfg
};
473 $opts->{pbs
} = $info->{pbs
};
475 if (!defined($opts->{'prune-backups'}) && !defined($opts->{maxfiles
})) {
476 $opts->{'prune-backups'} = $info->{'prune-backups'};
477 $opts->{maxfiles
} = $info->{maxfiles
};
480 } elsif ($opts->{dumpdir
}) {
481 $errors .= "dumpdir '$opts->{dumpdir}' does not exist"
482 if ! -d
$opts->{dumpdir
};
484 die "internal error";
487 if (!defined($opts->{'prune-backups'}) && !defined($opts->{maxfiles
})) {
488 $opts->{maxfiles
} = $defaults->{maxfiles
};
491 if ($opts->{tmpdir
} && ! -d
$opts->{tmpdir
}) {
492 $errors .= "\n" if $errors;
493 $errors .= "tmpdir '$opts->{tmpdir}' does not exist";
497 eval { $self->sendmail([], 0, $errors); };
498 debugmsg
('err', $@) if $@;
508 # Note: df 'available' can be negative, and percentage set to '-'
510 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
516 if (my ($fsid, $fstype, undef, $mp) = $line =~
517 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
526 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
533 my ($self, $upid) = @_;
537 my $maxwait = $self->{opts
}->{lockwait
} || $self->{lockwait
};
539 die "missing UPID" if !$upid; # should not happen
541 if (!open (SERVER_FLCK
, ">>$lockfile")) {
542 debugmsg
('err', "can't open lock on file '$lockfile' - $!", undef, 1);
543 die "can't open lock on file '$lockfile' - $!";
546 if (!flock (SERVER_FLCK
, LOCK_EX
|LOCK_NB
)) {
549 debugmsg
('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
550 die "can't acquire lock '$lockfile' (wait = 0)";
553 debugmsg
('info', "trying to get global lock - waiting...", undef, 1);
556 alarm ($maxwait * 60);
558 local $SIG{ALRM
} = sub { alarm (0); die "got timeout\n"; };
560 if (!flock (SERVER_FLCK
, LOCK_EX
)) {
573 debugmsg
('err', "can't acquire lock '$lockfile' - $err", undef, 1);
574 die "can't acquire lock '$lockfile' - $err";
577 debugmsg
('info', "got global lock", undef, 1);
580 PVE
::Tools
::file_set_contents
($pidfile, $upid);
583 sub run_hook_script
{
584 my ($self, $phase, $task, $logfd) = @_;
586 my $opts = $self->{opts
};
588 my $script = $opts->{script
};
592 die "The hook script '$script' is not executable.\n";
595 my $cmd = "$script $phase";
597 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
600 # set immutable opts directly (so they are available in all phases)
601 $ENV{STOREID
} = $opts->{storage
} if $opts->{storage
};
602 $ENV{DUMPDIR
} = $opts->{dumpdir
} if $opts->{dumpdir
};
604 foreach my $ek (qw(vmtype hostname target logfile)) {
605 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
607 # FIXME: for backwards compatibility - drop with PVE 7.0
608 $ENV{TARFILE
} = $task->{target
} if $task->{target
};
610 run_command
($logfd, $cmd);
613 sub compressor_info
{
615 my $opt_compress = $opts->{compress
};
617 if (!$opt_compress || $opt_compress eq '0') {
619 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
620 return ('lzop', 'lzo');
621 } elsif ($opt_compress eq 'gzip') {
622 if ($opts->{pigz
} > 0) {
623 my $pigz_threads = $opts->{pigz
};
624 if ($pigz_threads == 1) {
625 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
626 $pigz_threads = int(($cpuinfo->{cpus
} + 1)/2);
628 return ("pigz -p ${pigz_threads} --rsyncable", 'gz');
630 return ('gzip --rsyncable', 'gz');
632 } elsif ($opt_compress eq 'zstd') {
633 my $zstd_threads = $opts->{zstd
} // 1;
634 if ($zstd_threads == 0) {
635 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
636 $zstd_threads = int(($cpuinfo->{cpus
} + 1)/2);
638 return ("zstd --rsyncable --threads=${zstd_threads}", 'zst');
640 die "internal error - unknown compression option '$opt_compress'";
644 sub get_backup_file_list
{
645 my ($dir, $bkname, $exclude_fn) = @_;
648 foreach my $fn (<$dir/${bkname
}-*>) {
649 next if $exclude_fn && $fn eq $exclude_fn;
651 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
652 if ($archive_info->{is_std_name
}) {
653 my $filename = $archive_info->{filename
};
655 'path' => "$dir/$filename",
656 'ctime' => $archive_info->{ctime
},
658 push @{$bklist}, $backup;
665 sub exec_backup_task
{
666 my ($self, $task) = @_;
668 my $opts = $self->{opts
};
670 my $cfg = PVE
::Storage
::config
();
671 my $vmid = $task->{vmid
};
672 my $plugin = $task->{plugin
};
673 my $vmtype = $plugin->type();
675 $task->{backup_time
} = time();
678 my $pbs_snapshot_name;
680 if ($self->{opts
}->{pbs
}) {
681 if ($vmtype eq 'lxc') {
682 $pbs_group_name = "ct/$vmid";
683 } elsif ($vmtype eq 'qemu') {
684 $pbs_group_name = "vm/$vmid";
686 die "pbs backup not implemented for plugin type '$vmtype'\n";
688 my $btime = strftime
("%FT%TZ", gmtime($task->{backup_time
}));
689 $pbs_snapshot_name = "$pbs_group_name/$btime";
692 my $vmstarttime = time ();
698 my $log_vm_online_again = sub {
699 return if !defined($task->{vmstoptime
});
700 $task->{vmconttime
} //= time();
701 my $delay = $task->{vmconttime
} - $task->{vmstoptime
};
702 $delay = '<1' if $delay < 1;
703 debugmsg
('info', "guest is online again after $delay seconds", $logfd);
707 die "unable to find VM '$vmid'\n" if !$plugin;
709 # for now we deny backups of a running ha managed service in *stop* mode
710 # as it interferes with the HA stack (started services should not stop).
711 if ($opts->{mode
} eq 'stop' &&
712 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'started'))
714 die "Cannot execute a backup with stop mode on a HA managed and".
715 " enabled Service. Use snapshot mode or disable the Service.\n";
718 my $tmplog = "$logdir/$vmtype-$vmid.log";
720 my $bkname = "vzdump-$vmtype-$vmid";
721 my $basename = $bkname . strftime
("-%Y_%m_%d-%H_%M_%S", localtime($task->{backup_time
}));
723 my $maxfiles = $opts->{maxfiles
};
724 my $prune_options = $opts->{'prune-backups'};
726 my $backup_limit = 0;
727 if (defined($maxfiles)) {
728 $backup_limit = $maxfiles;
729 } elsif (defined($prune_options)) {
730 foreach my $keep (values %{$prune_options}) {
731 $backup_limit += $keep;
735 if ($backup_limit && !$opts->{remove
}) {
737 if ($self->{opts
}->{pbs
}) {
738 my $res = PVE
::Storage
::PBSPlugin
::run_client_cmd
($opts->{scfg
}, $opts->{storage
}, 'snapshots', $pbs_group_name);
739 $count = scalar(@$res);
741 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
742 $count = scalar(@$bklist);
744 die "There is a max backup limit of $backup_limit enforced by the".
745 " target storage or the vzdump parameters.".
746 " Either increase the limit or delete old backup(s).\n"
747 if $count >= $backup_limit;
750 if (!$self->{opts
}->{pbs
}) {
751 $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
754 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
755 my ($comp, $comp_ext) = compressor_info
($opts);
756 if ($comp && $comp_ext) {
757 $ext .= ".${comp_ext}";
760 if ($self->{opts
}->{pbs
}) {
761 die "unable to pipe backup to stdout\n" if $opts->{stdout
};
762 $task->{target
} = $pbs_snapshot_name;
764 if ($opts->{stdout
}) {
765 $task->{target
} = '-';
767 $task->{target
} = $task->{tmptar
} = "$opts->{dumpdir}/$basename$ext";
768 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
769 unlink $task->{tmptar
};
773 $task->{vmtype
} = $vmtype;
775 if ($opts->{tmpdir
}) {
776 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp$$";
777 } elsif ($self->{opts
}->{pbs
}) {
778 $task->{tmpdir
} = "/var/tmp/vzdumptmp$$"; #fixme
780 # dumpdir is posix? then use it as temporary dir
781 my $info = get_mount_info
($opts->{dumpdir
});
782 if ($vmtype eq 'qemu' ||
783 grep ($_ eq $info->{fstype
}, @posix_filesystems)) {
784 $task->{tmpdir
} = "$opts->{dumpdir}/$basename.tmp";
786 $task->{tmpdir
} = "/var/tmp/vzdumptmp$$";
787 debugmsg
('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
788 "using $task->{tmpdir} for temporary files", $logfd);
792 rmtree
$task->{tmpdir
};
793 mkdir $task->{tmpdir
};
794 -d
$task->{tmpdir
} ||
795 die "unable to create temporary directory '$task->{tmpdir}'";
797 $logfd = IO
::File-
>new (">$tmplog") ||
798 die "unable to create log file '$tmplog'";
800 $task->{dumpdir
} = $opts->{dumpdir
};
801 $task->{storeid
} = $opts->{storage
};
802 $task->{scfg
} = $opts->{scfg
};
803 $task->{tmplog
} = $tmplog;
805 unlink $task->{logfile
} if defined($task->{logfile
});
807 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
808 debugmsg
('info', "Backup started at " . strftime
("%F %H:%M:%S", localtime()));
810 $plugin->set_logfd ($logfd);
812 # test is VM is running
813 my ($running, $status_text) = $plugin->vm_status ($vmid);
815 debugmsg
('info', "status = ${status_text}", $logfd);
817 # lock VM (prevent config changes)
818 $plugin->lock_vm ($vmid);
820 $cleanup->{unlock
} = 1;
824 my $mode = $running ?
$task->{mode
} : 'stop';
826 if ($mode eq 'snapshot') {
827 my %saved_task = %$task;
828 eval { $plugin->prepare ($task, $vmid, $mode); };
830 die $err if $err !~ m/^mode failure/;
831 debugmsg
('info', $err, $logfd);
832 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
833 $mode = 'suspend'; # so prepare is called again below
834 %$task = %saved_task;
838 $cleanup->{prepared
} = 1;
840 $task->{mode
} = $mode;
842 debugmsg
('info', "backup mode: $mode", $logfd);
844 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
847 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
849 if ($mode eq 'stop') {
851 $plugin->prepare ($task, $vmid, $mode);
853 $self->run_hook_script ('backup-start', $task, $logfd);
856 debugmsg
('info', "stopping vm", $logfd);
857 $task->{vmstoptime
} = time();
858 $self->run_hook_script ('pre-stop', $task, $logfd);
859 $plugin->stop_vm ($task, $vmid);
860 $cleanup->{restart
} = 1;
864 } elsif ($mode eq 'suspend') {
866 $plugin->prepare ($task, $vmid, $mode);
868 $self->run_hook_script ('backup-start', $task, $logfd);
870 if ($vmtype eq 'lxc') {
872 $plugin->copy_data_phase1($task, $vmid);
875 debugmsg
('info', "suspending guest", $logfd);
876 $task->{vmstoptime
} = time ();
877 $self->run_hook_script ('pre-stop', $task, $logfd);
878 $plugin->suspend_vm ($task, $vmid);
879 $cleanup->{resume
} = 1;
881 if ($vmtype eq 'lxc') {
883 $plugin->copy_data_phase2($task, $vmid);
885 debugmsg
('info', "resuming guest", $logfd);
886 $cleanup->{resume
} = 0;
887 $self->run_hook_script('pre-restart', $task, $logfd);
888 $plugin->resume_vm($task, $vmid);
889 $self->run_hook_script('post-restart', $task, $logfd);
890 $log_vm_online_again->();
893 } elsif ($mode eq 'snapshot') {
895 $self->run_hook_script ('backup-start', $task, $logfd);
897 my $snapshot_count = $task->{snapshot_count
} || 0;
899 $self->run_hook_script ('pre-stop', $task, $logfd);
901 if ($snapshot_count > 1) {
902 debugmsg
('info', "suspend vm to make snapshot", $logfd);
903 $task->{vmstoptime
} = time ();
904 $plugin->suspend_vm ($task, $vmid);
905 $cleanup->{resume
} = 1;
908 $plugin->snapshot ($task, $vmid);
910 $self->run_hook_script ('pre-restart', $task, $logfd);
912 if ($snapshot_count > 1) {
913 debugmsg
('info', "resume vm", $logfd);
914 $cleanup->{resume
} = 0;
915 $plugin->resume_vm ($task, $vmid);
916 $log_vm_online_again->();
919 $self->run_hook_script ('post-restart', $task, $logfd);
922 die "internal error - unknown mode '$mode'\n";
925 # assemble archive image
926 $plugin->assemble ($task, $vmid);
930 if ($opts->{stdout
}) {
931 debugmsg
('info', "sending archive to stdout", $logfd);
932 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
933 $self->run_hook_script ('backup-end', $task, $logfd);
937 my $archive_txt = $self->{opts
}->{pbs
} ?
'Proxmox Backup Server' : 'vzdump';
938 debugmsg
('info', "creating $archive_txt archive '$task->{target}'", $logfd);
939 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
941 if ($self->{opts
}->{pbs
}) {
942 # size is added to task struct in guest vzdump plugins
944 rename ($task->{tmptar
}, $task->{target
}) ||
945 die "unable to rename '$task->{tmptar}' to '$task->{target}'\n";
948 $task->{size
} = (-s
$task->{target
}) || 0;
949 my $cs = format_size
($task->{size
});
950 debugmsg
('info', "archive file size: $cs", $logfd);
954 if ($opts->{remove
}) {
957 if ($self->{opts
}->{pbs
}) {
958 my $args = [$pbs_group_name, '--quiet', '1', '--keep-last', $maxfiles];
959 my $logfunc = sub { my $line = shift; debugmsg
('info', $line, $logfd); };
960 PVE
::Storage
::PBSPlugin
::run_raw_client_cmd
(
961 $opts->{scfg
}, $opts->{storage
}, 'prune', $args, logfunc
=> $logfunc);
963 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname, $task->{target
});
964 $bklist = [ sort { $b->{ctime
} <=> $a->{ctime
} } @$bklist ];
966 while (scalar (@$bklist) >= $maxfiles) {
967 my $d = pop @$bklist;
968 my $archive_path = $d->{path
};
969 debugmsg
('info', "delete old backup '$archive_path'", $logfd);
970 PVE
::Storage
::archive_remove
($archive_path);
973 } elsif (defined($prune_options)) {
974 my $logfunc = sub { debugmsg
($_[0], $_[1], $logfd) };
975 PVE
::Storage
::prune_backups
($cfg, $opts->{storage
}, $prune_options, $vmid, $vmtype, 0, $logfunc);
979 $self->run_hook_script ('backup-end', $task, $logfd);
986 if ($cleanup->{unlock
}) {
987 eval { $plugin->unlock_vm ($vmid); };
991 if ($cleanup->{prepared
}) {
992 # only call cleanup when necessary (when prepare was executed)
993 eval { $plugin->cleanup ($task, $vmid) };
997 eval { $plugin->set_logfd (undef); };
1000 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1002 $self->run_hook_script ('pre-restart', $task, $logfd);
1003 if ($cleanup->{resume
}) {
1004 debugmsg
('info', "resume vm", $logfd);
1005 $plugin->resume_vm ($task, $vmid);
1007 my $running = $plugin->vm_status($vmid);
1009 debugmsg
('info', "restarting vm", $logfd);
1010 $plugin->start_vm ($task, $vmid);
1013 $self->run_hook_script ('post-restart', $task, $logfd);
1019 $log_vm_online_again->();
1024 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1027 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1030 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1033 $task->{state} = 'err';
1034 $task->{msg
} = $err;
1035 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1036 debugmsg
('info', "Failed at " . strftime
("%F %H:%M:%S", localtime()));
1038 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1041 $task->{state} = 'ok';
1042 my $tstr = format_time
($delay);
1043 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1044 debugmsg
('info', "Backup finished at " . strftime
("%F %H:%M:%S", localtime()));
1047 close ($logfd) if $logfd;
1049 if ($task->{tmplog
}) {
1050 if ($self->{opts
}->{pbs
}) {
1051 if ($task->{state} eq 'ok') {
1052 my $param = [$pbs_snapshot_name, $task->{tmplog
}];
1053 PVE
::Storage
::PBSPlugin
::run_raw_client_cmd
(
1054 $opts->{scfg
}, $opts->{storage
}, 'upload-log', $param, errmsg
=> "upload log failed");
1056 } elsif ($task->{logfile
}) {
1057 system {'cp'} 'cp', $task->{tmplog
}, $task->{logfile
};
1061 eval { $self->run_hook_script ('log-end', $task); };
1063 die $err if $err && $err =~ m/^interrupted by signal$/;
1067 my ($self, $rpcenv, $authuser) = @_;
1069 my $opts = $self->{opts
};
1071 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1072 debugmsg
('info', "skip external VMs: " . join(', ', @{$self->{skiplist
}}))
1073 if scalar(@{$self->{skiplist
}});
1076 my $vzdump_plugins = {};
1077 foreach my $plugin (@{$self->{plugins
}}) {
1078 my $type = $plugin->type();
1079 next if exists $vzdump_plugins->{$type};
1080 $vzdump_plugins->{$type} = $plugin;
1083 my $vmlist = PVE
::Cluster
::get_vmlist
();
1084 foreach my $vmid (@{$opts->{vmids
}}) {
1085 my $guest_type = $vmlist->{ids
}->{$vmid}->{type
};
1086 my $plugin = $vzdump_plugins->{$guest_type};
1087 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], $opts->{all
});
1089 mode
=> $opts->{mode
},
1096 # Use in-memory files for the outer hook logs to pass them to sendmail.
1097 my $job_start_log = '';
1098 my $job_end_log = '';
1099 open my $job_start_fd, '>', \
$job_start_log;
1100 open my $job_end_fd, '>', \
$job_end_log;
1102 my $starttime = time();
1106 $self->run_hook_script ('job-start', undef, $job_start_fd);
1108 foreach my $task (@$tasklist) {
1109 $self->exec_backup_task ($task);
1110 $errcount += 1 if $task->{state} ne 'ok';
1113 $self->run_hook_script ('job-end', undef, $job_end_fd);
1117 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
1120 debugmsg
('err', "Backup job failed - $err", undef, 1);
1123 debugmsg
('info', "Backup job finished with errors", undef, 1);
1125 debugmsg
('info', "Backup job finished successfully", undef, 1);
1129 close $job_start_fd;
1132 my $totaltime = time() - $starttime;
1134 eval { $self->sendmail ($tasklist, $totaltime, undef, $job_start_log, $job_end_log); };
1135 debugmsg
('err', $@) if $@;
1139 die "job errors\n" if $errcount;
1147 return defined($confdesc->{$key});
1150 sub verify_vzdump_parameters
{
1151 my ($param, $check_missing) = @_;
1153 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1154 if $param->{all
} && $param->{vmid
};
1156 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1157 if $param->{exclude
} && $param->{vmid
};
1159 raise_param_exc
({ pool
=> "option conflicts with option 'vmid'"})
1160 if $param->{pool
} && $param->{vmid
};
1162 raise_param_exc
({ 'prune-backups' => "option conflicts with option 'maxfiles'"})
1163 if defined($param->{'prune-backups'}) && defined($param->{maxfiles
});
1165 $param->{'prune-backups'} = PVE
::JSONSchema
::parse_property_string
('prune-backups', $param->{'prune-backups'})
1166 if defined($param->{'prune-backups'});
1168 $param->{all
} = 1 if (defined($param->{exclude
}) && !$param->{pool
});
1170 warn "option 'size' is deprecated and will be removed in a future " .
1171 "release, please update your script/configuration!\n"
1172 if defined($param->{size
});
1174 return if !$check_missing;
1176 raise_param_exc
({ vmid
=> "property is missing"})
1177 if !($param->{all
} || $param->{stop
} || $param->{pool
}) && !$param->{vmid
};
1181 sub stop_running_backups
{
1184 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1187 my $task = PVE
::Tools
::upid_decode
($upid);
1189 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1190 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1191 kill(15, $task->{pid
});
1192 # wait max 15 seconds to shut down (else, do nothing for now)
1194 for ($i = 15; $i > 0; $i--) {
1195 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1198 die "stopping backup process $task->{pid} failed\n" if $i == 0;
1202 sub get_included_guests
{
1205 my $nodename = PVE
::INotify
::nodename
();
1207 my $vmids_per_node = {};
1209 my $vmlist = PVE
::Cluster
::get_vmlist
();
1212 $vmids = PVE
::API2Tools
::get_resource_pool_guest_members
($job->{pool
});
1213 } elsif ($job->{vmid
}) {
1214 $vmids = [ split_list
($job->{vmid
}) ];
1215 } elsif ($job->{all
}) {
1217 my $exclude = check_vmids
(split_list
($job->{exclude
}));
1218 my $excludehash = { map { $_ => 1 } @$exclude };
1220 for my $id (keys %{$vmlist->{ids
}}) {
1221 next if $excludehash->{$id};
1225 return $vmids_per_node;
1227 $vmids = check_vmids
(@$vmids);
1229 for my $vmid (@$vmids) {
1230 my $node = $vmlist->{ids
}->{$vmid}->{node
};
1231 next if (defined $job->{node
} && $job->{node
} ne $node);
1233 push @{$vmids_per_node->{$node}}, $vmid;
1236 return $vmids_per_node;