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);
72 my $parse_prune_backups_maxfiles = sub {
73 my ($param, $kind) = @_;
75 my $maxfiles = delete $param->{maxfiles
};
76 my $prune_backups = $param->{'prune-backups'};
78 debugmsg
('warn', "both 'maxfiles' and 'prune-backups' defined as ${kind} - ignoring 'maxfiles'")
79 if defined($maxfiles) && defined($prune_backups);
81 if (defined($prune_backups)) {
82 return if ref($prune_backups) eq 'HASH'; # already parsed
83 $param->{'prune-backups'} = PVE
::JSONSchema
::parse_property_string
(
87 } elsif (defined($maxfiles)) {
89 $param->{'prune-backups'} = { 'keep-last' => $maxfiles };
91 $param->{'prune-backups'} = { 'keep-all' => 1 };
99 my $cfg = PVE
::Storage
::config
();
100 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
101 my $type = $scfg->{type
};
103 die "can't use storage type '$type' for backup\n"
104 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'
105 || $type eq 'cifs' || $type eq 'cephfs' || $type eq 'pbs'));
106 die "can't use storage '$storage' for backups - wrong content type\n"
107 if (!$scfg->{content
}->{backup
});
109 PVE
::Storage
::activate_storage
($cfg, $storage);
115 $info->{'prune-backups'} = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'})
116 if defined($scfg->{'prune-backups'});
118 if ($type eq 'pbs') {
121 $info->{dumpdir
} = PVE
::Storage
::get_backup_dir
($cfg, $storage);
130 my $kb = $size / 1024;
133 return int ($kb) . "KB";
136 my $mb = $size / (1024*1024);
138 return int ($mb) . "MB";
142 return sprintf ("%.2fGB", $gb);
145 return sprintf ("%.2fTB", $tb);
151 my $hours = int ($seconds/3600);
152 $seconds = $seconds - $hours*3600;
153 my $min = int ($seconds/60);
154 $seconds = $seconds - $min*60;
156 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
162 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
180 foreach my $p (split (/:/, $ENV{PATH
})) {
187 die "unable to find command '$bin'\n";
194 for my $vmid (sort {$a <=> $b} @vmids) {
195 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
196 $vmid = int ($vmid); # remove leading zeros
205 sub read_vzdump_defaults
{
207 my $fn = "/etc/vzdump.conf";
211 my $default = $confdesc->{$_}->{default};
212 defined($default) ?
($_ => $default) : ()
215 $parse_prune_backups_maxfiles->($defaults, "defaults in VZDump schema");
218 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
219 return $defaults if $@;
221 my $conf_schema = { type
=> 'object', properties
=> $confdesc, };
222 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
223 if (my $excludes = $res->{'exclude-path'}) {
224 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
226 if (defined($res->{mailto
})) {
227 my @mailto = split_list
($res->{mailto
});
228 $res->{mailto
} = [ @mailto ];
230 $parse_prune_backups_maxfiles->($res, "options in '$fn'");
232 foreach my $key (keys %$defaults) {
233 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
236 if (defined($res->{storage
}) && defined($res->{dumpdir
})) {
237 debugmsg
('warn', "both 'storage' and 'dumpdir' defined in '$fn' - ignoring 'dumpdir'");
238 delete $res->{dumpdir
};
244 use constant MAX_MAIL_SIZE
=> 1024*1024;
246 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
248 my $opts = $self->{opts
};
250 my $mailto = $opts->{mailto
};
252 return if !($mailto && scalar(@$mailto));
254 my $cmdline = $self->{cmdline
};
257 foreach my $task (@$tasklist) {
258 $ecount++ if $task->{state} ne 'ok';
259 chomp $task->{msg
} if $task->{msg
};
260 $task->{backuptime
} = 0 if !$task->{backuptime
};
261 $task->{size
} = 0 if !$task->{size
};
262 $task->{target
} = 'unknown' if !$task->{target
};
263 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
265 if ($task->{state} eq 'todo') {
266 $task->{msg
} = 'aborted';
270 my $notify = $opts->{mailnotification
} || 'always';
271 return if (!$ecount && !$err && ($notify eq 'failure'));
273 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
276 $stat .= ": multiple problems";
283 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
287 my $text = $err ?
"$err\n\n" : '';
290 "%-10s %-${namelength}s %-6s %10s %10s %s\n",
291 qw(VMID NAME STATUS TIME SIZE FILENAME)
293 foreach my $task (@$tasklist) {
294 my $name = substr($task->{hostname
}, 0, $namelength);
295 my $successful = $task->{state} eq 'ok';
296 my $size = $successful ? format_size
($task->{size
}) : 0;
297 my $filename = $successful ?
$task->{target
} : '-';
298 my $size_fmt = $successful ?
"%10s": "%8.2fMB";
300 "%-10s %-${namelength}s %-6s %10s $size_fmt %s\n",
304 format_time
($task->{backuptime
}),
311 $text_log_part .= "\nDetailed backup logs:\n\n";
312 $text_log_part .= "$cmdline\n\n";
314 $text_log_part .= $detail_pre . "\n" if defined($detail_pre);
315 foreach my $task (@$tasklist) {
316 my $vmid = $task->{vmid
};
317 my $log = $task->{tmplog
};
319 $text_log_part .= "$vmid: no log available\n\n";
322 if (open (TMP
, "$log")) {
323 while (my $line = <TMP
>) {
324 next if $line =~ /^status: \d+/; # not useful in mails
325 $text_log_part .= encode8bit
("$vmid: $line");
328 $text_log_part .= "$vmid: Could not open log file\n\n";
331 $text_log_part .= "\n";
333 $text_log_part .= $detail_post if defined($detail_post);
336 my $html = "<html><body>\n";
337 $html .= "<p>" . (escape_html
($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
338 $html .= "<table border=1 cellpadding=3>\n";
339 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
343 foreach my $task (@$tasklist) {
344 my $vmid = $task->{vmid
};
345 my $name = $task->{hostname
};
347 if ($task->{state} eq 'ok') {
349 $ssize += $task->{size
};
351 $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
353 format_time
($task->{backuptime
}),
354 format_size
($task->{size
}),
355 escape_html
($task->{target
}));
357 $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
358 $vmid, $name, format_time
($task->{backuptime
}),
359 escape_html
($task->{msg
}));
363 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
364 format_time
($totaltime), format_size
($ssize));
366 $html .= "\n</table><br><br>\n";
368 $html_log_part .= "Detailed backup logs:<br /><br />\n";
369 $html_log_part .= "<pre>\n";
370 $html_log_part .= escape_html
($cmdline) . "\n\n";
372 $html_log_part .= escape_html
($detail_pre) . "\n" if defined($detail_pre);
373 foreach my $task (@$tasklist) {
374 my $vmid = $task->{vmid
};
375 my $log = $task->{tmplog
};
377 $html_log_part .= "$vmid: no log available\n\n";
380 if (open (TMP
, "$log")) {
381 while (my $line = <TMP
>) {
382 next if $line =~ /^status: \d+/; # not useful in mails
383 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
384 $html_log_part .= encode8bit
("$vmid: <font color=red>".
385 escape_html
($line) . "</font>");
387 $html_log_part .= encode8bit
("$vmid: " . escape_html
($line));
391 $html_log_part .= "$vmid: Could not open log file\n\n";
394 $html_log_part .= "\n";
396 $html_log_part .= escape_html
($detail_post) if defined($detail_post);
397 $html_log_part .= "</pre>";
398 my $html_end = "\n</body></html>\n";
401 if (length($text) + length($text_log_part) +
402 length($html) + length($html_log_part) +
403 length($html_end) < MAX_MAIL_SIZE
)
405 $html .= $html_log_part;
407 $text .= $text_log_part;
409 my $msg = "Log output was too long to be sent by mail. ".
410 "See Task History for details!\n";
412 $html .= "<p>$msg</p>";
416 my $subject = "vzdump backup status ($hostname) : $stat";
418 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
419 my $mailfrom = $dcconf->{email_from
} || "root";
421 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
425 my ($class, $cmdline, $opts, $skiplist) = @_;
431 check_bin
('sendmail');
435 check_bin
('umount');
436 check_bin
('cstream');
437 check_bin
('ionice');
439 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
440 check_bin
('lvcreate');
442 check_bin
('lvremove');
445 my $defaults = read_vzdump_defaults
();
447 $opts->{remove
} = 1 if !defined($opts->{remove
});
449 foreach my $k (keys %$defaults) {
450 next if $k eq 'exclude-path' || $k eq 'prune-backups'; # dealt with separately
451 if ($k eq 'dumpdir' || $k eq 'storage') {
452 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
453 !defined ($opts->{storage
});
455 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
459 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
460 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
462 $skiplist = [] if !$skiplist;
463 my $self = bless { cmdline
=> $cmdline, opts
=> $opts, skiplist
=> $skiplist };
465 my $findexcl = $self->{findexcl
} = [];
466 if ($defaults->{'exclude-path'}) {
467 push @$findexcl, @{$defaults->{'exclude-path'}};
470 if ($opts->{'exclude-path'}) {
471 push @$findexcl, @{$opts->{'exclude-path'}};
474 if ($opts->{stdexcludes
}) {
475 push @$findexcl, '/tmp/?*',
480 foreach my $p (@plugins) {
482 my $pd = $p->new ($self);
484 push @{$self->{plugins
}}, $pd;
487 if (defined($opts->{storage
}) && $opts->{stdout
}) {
488 die "cannot use options 'storage' and 'stdout' at the same time\n";
489 } elsif (defined($opts->{storage
}) && defined($opts->{dumpdir
})) {
490 die "cannot use options 'storage' and 'dumpdir' at the same time\n";
493 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
494 $opts->{storage
} = 'local';
499 if ($opts->{storage
}) {
500 my $info = eval { storage_info
($opts->{storage
}) };
503 $errors .= "could not get storage information for '$opts->{storage}': $err";
505 $opts->{dumpdir
} = $info->{dumpdir
};
506 $opts->{scfg
} = $info->{scfg
};
507 $opts->{pbs
} = $info->{pbs
};
508 $opts->{'prune-backups'} //= $info->{'prune-backups'};
510 } elsif ($opts->{dumpdir
}) {
511 $errors .= "dumpdir '$opts->{dumpdir}' does not exist"
512 if ! -d
$opts->{dumpdir
};
514 die "internal error";
517 $opts->{'prune-backups'} //= $defaults->{'prune-backups'};
519 # avoid triggering any remove code path if keep-all is set
520 $opts->{remove
} = 0 if $opts->{'prune-backups'}->{'keep-all'};
522 if ($opts->{tmpdir
} && ! -d
$opts->{tmpdir
}) {
523 $errors .= "\n" if $errors;
524 $errors .= "tmpdir '$opts->{tmpdir}' does not exist";
528 eval { $self->sendmail([], 0, $errors); };
529 debugmsg
('err', $@) if $@;
539 # Note: df 'available' can be negative, and percentage set to '-'
541 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
547 if (my ($fsid, $fstype, undef, $mp) = $line =~
548 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
557 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
564 my ($self, $upid) = @_;
568 my $maxwait = $self->{opts
}->{lockwait
} || $self->{lockwait
};
570 die "missing UPID" if !$upid; # should not happen
572 if (!open (SERVER_FLCK
, ">>$lockfile")) {
573 debugmsg
('err', "can't open lock on file '$lockfile' - $!", undef, 1);
574 die "can't open lock on file '$lockfile' - $!";
577 if (!flock (SERVER_FLCK
, LOCK_EX
|LOCK_NB
)) {
580 debugmsg
('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
581 die "can't acquire lock '$lockfile' (wait = 0)";
584 debugmsg
('info', "trying to get global lock - waiting...", undef, 1);
587 alarm ($maxwait * 60);
589 local $SIG{ALRM
} = sub { alarm (0); die "got timeout\n"; };
591 if (!flock (SERVER_FLCK
, LOCK_EX
)) {
604 debugmsg
('err', "can't acquire lock '$lockfile' - $err", undef, 1);
605 die "can't acquire lock '$lockfile' - $err";
608 debugmsg
('info', "got global lock", undef, 1);
611 PVE
::Tools
::file_set_contents
($pidfile, $upid);
614 sub run_hook_script
{
615 my ($self, $phase, $task, $logfd) = @_;
617 my $opts = $self->{opts
};
619 my $script = $opts->{script
};
623 die "The hook script '$script' is not executable.\n";
626 my $cmd = "$script $phase";
628 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
631 # set immutable opts directly (so they are available in all phases)
632 $ENV{STOREID
} = $opts->{storage
} if $opts->{storage
};
633 $ENV{DUMPDIR
} = $opts->{dumpdir
} if $opts->{dumpdir
};
635 foreach my $ek (qw(vmtype hostname target logfile)) {
636 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
638 # FIXME: for backwards compatibility - drop with PVE 7.0
639 $ENV{TARFILE
} = $task->{target
} if $task->{target
};
641 run_command
($logfd, $cmd);
644 sub compressor_info
{
646 my $opt_compress = $opts->{compress
};
648 if (!$opt_compress || $opt_compress eq '0') {
650 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
651 return ('lzop', 'lzo');
652 } elsif ($opt_compress eq 'gzip') {
653 if ($opts->{pigz
} > 0) {
654 my $pigz_threads = $opts->{pigz
};
655 if ($pigz_threads == 1) {
656 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
657 $pigz_threads = int(($cpuinfo->{cpus
} + 1)/2);
659 return ("pigz -p ${pigz_threads} --rsyncable", 'gz');
661 return ('gzip --rsyncable', 'gz');
663 } elsif ($opt_compress eq 'zstd') {
664 my $zstd_threads = $opts->{zstd
} // 1;
665 if ($zstd_threads == 0) {
666 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
667 $zstd_threads = int(($cpuinfo->{cpus
} + 1)/2);
669 return ("zstd --rsyncable --threads=${zstd_threads}", 'zst');
671 die "internal error - unknown compression option '$opt_compress'";
675 sub get_backup_file_list
{
676 my ($dir, $bkname, $exclude_fn) = @_;
679 foreach my $fn (<$dir/${bkname
}-*>) {
680 next if $exclude_fn && $fn eq $exclude_fn;
682 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
683 if ($archive_info->{is_std_name
}) {
684 my $filename = $archive_info->{filename
};
686 'path' => "$dir/$filename",
687 'ctime' => $archive_info->{ctime
},
689 push @{$bklist}, $backup;
696 sub exec_backup_task
{
697 my ($self, $task) = @_;
699 my $opts = $self->{opts
};
701 my $cfg = PVE
::Storage
::config
();
702 my $vmid = $task->{vmid
};
703 my $plugin = $task->{plugin
};
705 $task->{backup_time
} = time();
708 my $pbs_snapshot_name;
710 my $vmstarttime = time ();
716 my $log_vm_online_again = sub {
717 return if !defined($task->{vmstoptime
});
718 $task->{vmconttime
} //= time();
719 my $delay = $task->{vmconttime
} - $task->{vmstoptime
};
720 $delay = '<1' if $delay < 1;
721 debugmsg
('info', "guest is online again after $delay seconds", $logfd);
725 die "unable to find VM '$vmid'\n" if !$plugin;
727 my $vmtype = $plugin->type();
729 if ($self->{opts
}->{pbs
}) {
730 if ($vmtype eq 'lxc') {
731 $pbs_group_name = "ct/$vmid";
732 } elsif ($vmtype eq 'qemu') {
733 $pbs_group_name = "vm/$vmid";
735 die "pbs backup not implemented for plugin type '$vmtype'\n";
737 my $btime = strftime
("%FT%TZ", gmtime($task->{backup_time
}));
738 $pbs_snapshot_name = "$pbs_group_name/$btime";
741 # for now we deny backups of a running ha managed service in *stop* mode
742 # as it interferes with the HA stack (started services should not stop).
743 if ($opts->{mode
} eq 'stop' &&
744 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'started'))
746 die "Cannot execute a backup with stop mode on a HA managed and".
747 " enabled Service. Use snapshot mode or disable the Service.\n";
750 my $tmplog = "$logdir/$vmtype-$vmid.log";
752 my $bkname = "vzdump-$vmtype-$vmid";
753 my $basename = $bkname . strftime
("-%Y_%m_%d-%H_%M_%S", localtime($task->{backup_time
}));
755 my $prune_options = $opts->{'prune-backups'};
757 my $backup_limit = 0;
758 if (!$prune_options->{'keep-all'}) {
759 foreach my $keep (values %{$prune_options}) {
760 $backup_limit += $keep;
764 if ($backup_limit && !$opts->{remove
}) {
766 if ($self->{opts
}->{pbs
}) {
767 my $res = PVE
::Storage
::PBSPlugin
::run_client_cmd
($opts->{scfg
}, $opts->{storage
}, 'snapshots', $pbs_group_name);
768 $count = scalar(@$res);
770 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
771 $count = scalar(@$bklist);
773 die "There is a max backup limit of $backup_limit enforced by the".
774 " target storage or the vzdump parameters.".
775 " Either increase the limit or delete old backup(s).\n"
776 if $count >= $backup_limit;
779 if (!$self->{opts
}->{pbs
}) {
780 $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
783 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
784 my ($comp, $comp_ext) = compressor_info
($opts);
785 if ($comp && $comp_ext) {
786 $ext .= ".${comp_ext}";
789 if ($self->{opts
}->{pbs
}) {
790 die "unable to pipe backup to stdout\n" if $opts->{stdout
};
791 $task->{target
} = $pbs_snapshot_name;
793 if ($opts->{stdout
}) {
794 $task->{target
} = '-';
796 $task->{target
} = $task->{tmptar
} = "$opts->{dumpdir}/$basename$ext";
797 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
798 unlink $task->{tmptar
};
802 $task->{vmtype
} = $vmtype;
805 if ($opts->{tmpdir
}) {
806 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp${pid}_$vmid/";
807 } elsif ($self->{opts
}->{pbs
}) {
808 $task->{tmpdir
} = "/var/tmp/vzdumptmp${pid}_$vmid";
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";
816 $task->{tmpdir
} = "/var/tmp/vzdumptmp${pid}_$vmid";
817 debugmsg
('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
818 "using $task->{tmpdir} for temporary files", $logfd);
822 rmtree
$task->{tmpdir
};
823 mkdir $task->{tmpdir
};
824 -d
$task->{tmpdir
} ||
825 die "unable to create temporary directory '$task->{tmpdir}'";
827 $logfd = IO
::File-
>new (">$tmplog") ||
828 die "unable to create log file '$tmplog'";
830 $task->{dumpdir
} = $opts->{dumpdir
};
831 $task->{storeid
} = $opts->{storage
};
832 $task->{scfg
} = $opts->{scfg
};
833 $task->{tmplog
} = $tmplog;
835 unlink $task->{logfile
} if defined($task->{logfile
});
837 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
838 debugmsg
('info', "Backup started at " . strftime
("%F %H:%M:%S", localtime()));
840 $plugin->set_logfd ($logfd);
842 # test is VM is running
843 my ($running, $status_text) = $plugin->vm_status ($vmid);
845 debugmsg
('info', "status = ${status_text}", $logfd);
847 # lock VM (prevent config changes)
848 $plugin->lock_vm ($vmid);
850 $cleanup->{unlock
} = 1;
854 my $mode = $running ?
$task->{mode
} : 'stop';
856 if ($mode eq 'snapshot') {
857 my %saved_task = %$task;
858 eval { $plugin->prepare ($task, $vmid, $mode); };
860 die $err if $err !~ m/^mode failure/;
861 debugmsg
('info', $err, $logfd);
862 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
863 $mode = 'suspend'; # so prepare is called again below
864 %$task = %saved_task;
868 $cleanup->{prepared
} = 1;
870 $task->{mode
} = $mode;
872 debugmsg
('info', "backup mode: $mode", $logfd);
874 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
877 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
879 if ($mode eq 'stop') {
881 $plugin->prepare ($task, $vmid, $mode);
883 $self->run_hook_script ('backup-start', $task, $logfd);
886 debugmsg
('info', "stopping vm", $logfd);
887 $task->{vmstoptime
} = time();
888 $self->run_hook_script ('pre-stop', $task, $logfd);
889 $plugin->stop_vm ($task, $vmid);
890 $cleanup->{restart
} = 1;
894 } elsif ($mode eq 'suspend') {
896 $plugin->prepare ($task, $vmid, $mode);
898 $self->run_hook_script ('backup-start', $task, $logfd);
900 if ($vmtype eq 'lxc') {
902 $plugin->copy_data_phase1($task, $vmid);
905 debugmsg
('info', "suspending guest", $logfd);
906 $task->{vmstoptime
} = time ();
907 $self->run_hook_script ('pre-stop', $task, $logfd);
908 $plugin->suspend_vm ($task, $vmid);
909 $cleanup->{resume
} = 1;
911 if ($vmtype eq 'lxc') {
913 $plugin->copy_data_phase2($task, $vmid);
915 debugmsg
('info', "resuming guest", $logfd);
916 $cleanup->{resume
} = 0;
917 $self->run_hook_script('pre-restart', $task, $logfd);
918 $plugin->resume_vm($task, $vmid);
919 $self->run_hook_script('post-restart', $task, $logfd);
920 $log_vm_online_again->();
923 } elsif ($mode eq 'snapshot') {
925 $self->run_hook_script ('backup-start', $task, $logfd);
927 my $snapshot_count = $task->{snapshot_count
} || 0;
929 $self->run_hook_script ('pre-stop', $task, $logfd);
931 if ($snapshot_count > 1) {
932 debugmsg
('info', "suspend vm to make snapshot", $logfd);
933 $task->{vmstoptime
} = time ();
934 $plugin->suspend_vm ($task, $vmid);
935 $cleanup->{resume
} = 1;
938 $plugin->snapshot ($task, $vmid);
940 $self->run_hook_script ('pre-restart', $task, $logfd);
942 if ($snapshot_count > 1) {
943 debugmsg
('info', "resume vm", $logfd);
944 $cleanup->{resume
} = 0;
945 $plugin->resume_vm ($task, $vmid);
946 $log_vm_online_again->();
949 $self->run_hook_script ('post-restart', $task, $logfd);
952 die "internal error - unknown mode '$mode'\n";
955 # assemble archive image
956 $plugin->assemble ($task, $vmid);
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);
967 my $archive_txt = $self->{opts
}->{pbs
} ?
'Proxmox Backup Server' : 'vzdump';
968 debugmsg
('info', "creating $archive_txt archive '$task->{target}'", $logfd);
969 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
971 if ($self->{opts
}->{pbs
}) {
972 # size is added to task struct in guest vzdump plugins
974 rename ($task->{tmptar
}, $task->{target
}) ||
975 die "unable to rename '$task->{tmptar}' to '$task->{target}'\n";
978 $task->{size
} = (-s
$task->{target
}) || 0;
979 my $cs = format_size
($task->{size
});
980 debugmsg
('info', "archive file size: $cs", $logfd);
984 if ($opts->{remove
}) {
985 if (!defined($opts->{storage
})) {
986 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname, $task->{target
});
987 PVE
::Storage
::prune_mark_backup_group
($bklist, $prune_options);
989 foreach my $prune_entry (@{$bklist}) {
990 next if $prune_entry->{mark
} ne 'remove';
992 my $archive_path = $prune_entry->{path
};
993 debugmsg
('info', "delete old backup '$archive_path'", $logfd);
994 PVE
::Storage
::archive_remove
($archive_path);
997 my $logfunc = sub { debugmsg
($_[0], $_[1], $logfd) };
998 PVE
::Storage
::prune_backups
($cfg, $opts->{storage
}, $prune_options, $vmid, $vmtype, 0, $logfunc);
1002 $self->run_hook_script ('backup-end', $task, $logfd);
1009 if ($cleanup->{unlock
}) {
1010 eval { $plugin->unlock_vm ($vmid); };
1014 if ($cleanup->{prepared
}) {
1015 # only call cleanup when necessary (when prepare was executed)
1016 eval { $plugin->cleanup ($task, $vmid) };
1020 eval { $plugin->set_logfd (undef); };
1023 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1025 $self->run_hook_script ('pre-restart', $task, $logfd);
1026 if ($cleanup->{resume
}) {
1027 debugmsg
('info', "resume vm", $logfd);
1028 $plugin->resume_vm ($task, $vmid);
1030 my $running = $plugin->vm_status($vmid);
1032 debugmsg
('info', "restarting vm", $logfd);
1033 $plugin->start_vm ($task, $vmid);
1036 $self->run_hook_script ('post-restart', $task, $logfd);
1042 $log_vm_online_again->();
1047 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1050 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1053 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1056 $task->{state} = 'err';
1057 $task->{msg
} = $err;
1058 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1059 debugmsg
('info', "Failed at " . strftime
("%F %H:%M:%S", localtime()));
1061 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1064 $task->{state} = 'ok';
1065 my $tstr = format_time
($delay);
1066 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1067 debugmsg
('info', "Backup finished at " . strftime
("%F %H:%M:%S", localtime()));
1070 close ($logfd) if $logfd;
1072 if ($task->{tmplog
}) {
1073 if ($self->{opts
}->{pbs
}) {
1074 if ($task->{state} eq 'ok') {
1075 my $param = [$pbs_snapshot_name, $task->{tmplog
}];
1076 PVE
::Storage
::PBSPlugin
::run_raw_client_cmd
(
1077 $opts->{scfg
}, $opts->{storage
}, 'upload-log', $param, errmsg
=> "upload log failed");
1079 } elsif ($task->{logfile
}) {
1080 system {'cp'} 'cp', $task->{tmplog
}, $task->{logfile
};
1084 eval { $self->run_hook_script ('log-end', $task); };
1086 die $err if $err && $err =~ m/^interrupted by signal$/;
1090 my ($self, $rpcenv, $authuser) = @_;
1092 my $opts = $self->{opts
};
1094 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1096 if (scalar(@{$self->{skiplist
}})) {
1097 my $skip_string = join(', ', sort { $a <=> $b } @{$self->{skiplist
}});
1098 debugmsg
('info', "skip external VMs: $skip_string");
1102 my $vzdump_plugins = {};
1103 foreach my $plugin (@{$self->{plugins
}}) {
1104 my $type = $plugin->type();
1105 next if exists $vzdump_plugins->{$type};
1106 $vzdump_plugins->{$type} = $plugin;
1109 my $vmlist = PVE
::Cluster
::get_vmlist
();
1110 my $vmids = [ sort { $a <=> $b } @{$opts->{vmids
}} ];
1111 foreach my $vmid (@{$vmids}) {
1113 if (defined($vmlist->{ids
}->{$vmid})) {
1114 my $guest_type = $vmlist->{ids
}->{$vmid}->{type
};
1115 $plugin = $vzdump_plugins->{$guest_type};
1116 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], $opts->{all
});
1119 mode
=> $opts->{mode
},
1126 # Use in-memory files for the outer hook logs to pass them to sendmail.
1127 my $job_start_log = '';
1128 my $job_end_log = '';
1129 open my $job_start_fd, '>', \
$job_start_log;
1130 open my $job_end_fd, '>', \
$job_end_log;
1132 my $starttime = time();
1136 $self->run_hook_script ('job-start', undef, $job_start_fd);
1138 foreach my $task (@$tasklist) {
1139 $self->exec_backup_task ($task);
1140 $errcount += 1 if $task->{state} ne 'ok';
1143 $self->run_hook_script ('job-end', undef, $job_end_fd);
1147 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
1150 debugmsg
('err', "Backup job failed - $err", undef, 1);
1153 debugmsg
('info', "Backup job finished with errors", undef, 1);
1155 debugmsg
('info', "Backup job finished successfully", undef, 1);
1159 close $job_start_fd;
1162 my $totaltime = time() - $starttime;
1164 eval { $self->sendmail ($tasklist, $totaltime, undef, $job_start_log, $job_end_log); };
1165 debugmsg
('err', $@) if $@;
1169 die "job errors\n" if $errcount;
1177 return defined($confdesc->{$key});
1180 sub verify_vzdump_parameters
{
1181 my ($param, $check_missing) = @_;
1183 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1184 if $param->{all
} && $param->{vmid
};
1186 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1187 if $param->{exclude
} && $param->{vmid
};
1189 raise_param_exc
({ pool
=> "option conflicts with option 'vmid'"})
1190 if $param->{pool
} && $param->{vmid
};
1192 raise_param_exc
({ 'prune-backups' => "option conflicts with option 'maxfiles'"})
1193 if defined($param->{'prune-backups'}) && defined($param->{maxfiles
});
1195 $parse_prune_backups_maxfiles->($param, 'CLI parameters');
1197 $param->{all
} = 1 if (defined($param->{exclude
}) && !$param->{pool
});
1199 warn "option 'size' is deprecated and will be removed in a future " .
1200 "release, please update your script/configuration!\n"
1201 if defined($param->{size
});
1203 return if !$check_missing;
1205 raise_param_exc
({ vmid
=> "property is missing"})
1206 if !($param->{all
} || $param->{stop
} || $param->{pool
}) && !$param->{vmid
};
1210 sub stop_running_backups
{
1213 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1216 my $task = PVE
::Tools
::upid_decode
($upid);
1218 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1219 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1220 kill(15, $task->{pid
});
1221 # wait max 15 seconds to shut down (else, do nothing for now)
1223 for ($i = 15; $i > 0; $i--) {
1224 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1227 die "stopping backup process $task->{pid} failed\n" if $i == 0;
1231 sub get_included_guests
{
1235 my $vmids_per_node = {};
1237 my $vmlist = PVE
::Cluster
::get_vmlist
();
1240 $vmids = PVE
::API2Tools
::get_resource_pool_guest_members
($job->{pool
});
1241 } elsif ($job->{vmid
}) {
1242 $vmids = [ split_list
($job->{vmid
}) ];
1243 } elsif ($job->{all
}) {
1245 my $exclude = check_vmids
(split_list
($job->{exclude
}));
1246 my $excludehash = { map { $_ => 1 } @$exclude };
1248 for my $id (keys %{$vmlist->{ids
}}) {
1249 next if $excludehash->{$id};
1253 return $vmids_per_node;
1255 $vmids = check_vmids
(@$vmids);
1257 for my $vmid (@$vmids) {
1258 if (defined($vmlist->{ids
}->{$vmid})) {
1259 my $node = $vmlist->{ids
}->{$vmid}->{node
};
1260 next if (defined $job->{node
} && $job->{node
} ne $node);
1262 push @{$vmids_per_node->{$node}}, $vmid;
1264 push @{$vmids_per_node->{''}}, $vmid;
1268 return $vmids_per_node;