]> git.proxmox.com Git - pve-manager.git/blobdiff - PVE/VZDump.pm
vzdump: remove deprecated size parameter
[pve-manager.git] / PVE / VZDump.pm
index ada3681ec629996a3b65bd931194f6f07af4ef58..8213ed665155eeb0f3313bcaa564ab7141b81092 100644 (file)
@@ -21,6 +21,8 @@ use PVE::RPCEnvironment;
 use PVE::Storage;
 use PVE::VZDump::Common;
 use PVE::VZDump::Plugin;
+use PVE::Tools qw(extract_param split_list);
+use PVE::API2Tools;
 
 my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
 
@@ -67,6 +69,30 @@ sub run_command {
     PVE::Tools::run_command($cmdstr, %param, logfunc => $logfunc);
 }
 
+my $parse_prune_backups_maxfiles = sub {
+    my ($param, $kind) = @_;
+
+    my $maxfiles = delete $param->{maxfiles};
+    my $prune_backups = $param->{'prune-backups'};
+
+    debugmsg('warn', "both 'maxfiles' and 'prune-backups' defined as ${kind} - ignoring 'maxfiles'")
+        if defined($maxfiles) && defined($prune_backups);
+
+    if (defined($prune_backups)) {
+       return if ref($prune_backups) eq 'HASH'; # already parsed
+       $param->{'prune-backups'} = PVE::JSONSchema::parse_property_string(
+           'prune-backups',
+           $prune_backups
+       );
+    } elsif (defined($maxfiles)) {
+       if ($maxfiles) {
+           $param->{'prune-backups'} = { 'keep-last' => $maxfiles };
+       } else {
+           $param->{'prune-backups'} = { 'keep-all' => 1 };
+       }
+    }
+};
+
 sub storage_info {
     my $storage = shift;
 
@@ -80,20 +106,20 @@ sub storage_info {
     die "can't use storage '$storage' for backups - wrong content type\n"
        if (!$scfg->{content}->{backup});
 
-    PVE::Storage::activate_storage($cfg, $storage);
+    my $info = {
+       scfg => $scfg,
+    };
+
+    $info->{'prune-backups'} = PVE::JSONSchema::parse_property_string('prune-backups', $scfg->{'prune-backups'})
+       if defined($scfg->{'prune-backups'});
 
     if ($type eq 'pbs') {
-       return {
-           scfg => $scfg,
-           maxfiles => $scfg->{maxfiles},
-       };
+       $info->{pbs} = 1;
     } else {
-       return {
-           scfg => $scfg,
-           dumpdir => PVE::Storage::get_backup_dir($cfg, $storage),
-           maxfiles => $scfg->{maxfiles},
-       };
+       $info->{dumpdir} = PVE::Storage::get_backup_dir($cfg, $storage);
     }
+
+    return $info;
 }
 
 sub format_size {
@@ -106,13 +132,15 @@ sub format_size {
     }
 
     my $mb = $size / (1024*1024);
-
     if ($mb < 1024) {
        return int ($mb) . "MB";
-    } else {
-       my $gb = $mb / 1024;
+    }
+    my $gb = $mb / 1024;
+    if ($gb < 1024) {
        return sprintf ("%.2fGB", $gb);
     }
+    my $tb = $gb / 1024;
+    return sprintf ("%.2fTB", $tb);
 }
 
 sub format_time {
@@ -161,7 +189,7 @@ sub check_vmids {
     my (@vmids) = @_;
 
     my $res = [];
-    foreach my $vmid (@vmids) {
+    for my $vmid (sort {$a <=> $b} @vmids) {
        die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
        $vmid = int ($vmid); # remove leading zeros
        next if !$vmid;
@@ -182,6 +210,7 @@ sub read_vzdump_defaults {
             defined($default) ? ($_ => $default) : ()
        } keys %$confdesc
     };
+    $parse_prune_backups_maxfiles->($defaults, "defaults in VZDump schema");
 
     my $raw;
     eval { $raw = PVE::Tools::file_get_contents($fn); };
@@ -193,14 +222,20 @@ sub read_vzdump_defaults {
        $res->{'exclude-path'} = PVE::Tools::split_args($excludes);
     }
     if (defined($res->{mailto})) {
-       my @mailto = PVE::Tools::split_list($res->{mailto});
+       my @mailto = split_list($res->{mailto});
        $res->{mailto} = [ @mailto ];
     }
+    $parse_prune_backups_maxfiles->($res, "options in '$fn'");
 
     foreach my $key (keys %$defaults) {
        $res->{$key} = $defaults->{$key} if !defined($res->{$key});
     }
 
+    if (defined($res->{storage}) && defined($res->{dumpdir})) {
+       debugmsg('warn', "both 'storage' and 'dumpdir' defined in '$fn' - ignoring 'dumpdir'");
+       delete $res->{dumpdir};
+    }
+
     return $res;
 }
 
@@ -222,7 +257,7 @@ sub sendmail {
        chomp $task->{msg} if $task->{msg};
        $task->{backuptime} = 0 if !$task->{backuptime};
        $task->{size} = 0 if !$task->{size};
-       $task->{tarfile} = 'unknown' if !$task->{tarfile};
+       $task->{target} = 'unknown' if !$task->{target};
        $task->{hostname} = "VM $task->{vmid}" if !$task->{hostname};
 
        if ($task->{state} eq 'todo') {
@@ -248,22 +283,26 @@ sub sendmail {
 
     # text part
     my $text = $err ? "$err\n\n" : '';
-    $text .= sprintf ("%-10s %-6s %10s %10s  %s\n", qw(VMID STATUS TIME SIZE FILENAME));
+    my $namelength = 20;
+    $text .= sprintf (
+       "%-10s %-${namelength}s %-6s %10s %10s  %s\n",
+       qw(VMID NAME STATUS TIME SIZE FILENAME)
+    );
     foreach my $task (@$tasklist) {
-       my $vmid = $task->{vmid};
-       if  ($task->{state} eq 'ok') {
-
-           $text .= sprintf ("%-10s %-6s %10s %10s  %s\n", $vmid,
-                               $task->{state},
-                               format_time($task->{backuptime}),
-                               format_size ($task->{size}),
-                               $task->{tarfile});
-       } else {
-           $text .= sprintf ("%-10s %-6s %10s %8.2fMB  %s\n", $vmid,
-                               $task->{state},
-                               format_time($task->{backuptime}),
-                               0, '-');
-       }
+       my $name = substr($task->{hostname}, 0, $namelength);
+       my $successful = $task->{state} eq 'ok';
+       my $size = $successful ? format_size ($task->{size}) : 0;
+       my $filename = $successful ? $task->{target} : '-';
+       my $size_fmt = $successful ? "%10s": "%8.2fMB";
+       $text .= sprintf(
+           "%-10s %-${namelength}s %-6s %10s $size_fmt  %s\n",
+           $task->{vmid},
+           $name,
+           $task->{state},
+           format_time($task->{backuptime}),
+           $size,
+           $filename,
+       );
     }
 
     my $text_log_part;
@@ -278,15 +317,15 @@ sub sendmail {
            $text_log_part .= "$vmid: no log available\n\n";
            next;
        }
-       if (open (TMP, "$log")) {
-           while (my $line = <TMP>) {
+       if (open (my $TMP, '<', "$log")) {
+           while (my $line = <$TMP>) {
                next if $line =~ /^status: \d+/; # not useful in mails
                $text_log_part .= encode8bit ("$vmid: $line");
            }
+           close ($TMP);
        } else {
            $text_log_part .= "$vmid: Could not open log file\n\n";
        }
-       close (TMP);
        $text_log_part .= "\n";
     }
     $text_log_part .= $detail_post if defined($detail_post);
@@ -298,24 +337,29 @@ sub sendmail {
     $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
 
     my $ssize = 0;
-
     foreach my $task (@$tasklist) {
        my $vmid = $task->{vmid};
        my $name = $task->{hostname};
 
        if  ($task->{state} eq 'ok') {
-
            $ssize += $task->{size};
 
-           $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
-                               $vmid, $name,
-                               format_time($task->{backuptime}),
-                               format_size ($task->{size}),
-                               escape_html ($task->{tarfile}));
+           $html .= sprintf (
+               "<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
+               $vmid,
+               $name,
+               format_time($task->{backuptime}),
+               format_size ($task->{size}),
+               escape_html ($task->{target}),
+           );
        } else {
-           $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
-                               $vmid, $name, format_time($task->{backuptime}),
-                               escape_html ($task->{msg}));
+           $html .= sprintf (
+               "<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
+               $vmid,
+               $name,
+               format_time($task->{backuptime}),
+               escape_html ($task->{msg}),
+           );
        }
     }
 
@@ -336,8 +380,8 @@ sub sendmail {
            $html_log_part .= "$vmid: no log available\n\n";
            next;
        }
-       if (open (TMP, "$log")) {
-           while (my $line = <TMP>) {
+       if (open (my $TMP, '<', "$log")) {
+           while (my $line = <$TMP>) {
                next if $line =~ /^status: \d+/; # not useful in mails
                if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
                    $html_log_part .= encode8bit ("$vmid: <font color=red>".
@@ -346,21 +390,23 @@ sub sendmail {
                    $html_log_part .= encode8bit ("$vmid: " . escape_html ($line));
                }
            }
+           close ($TMP);
        } else {
            $html_log_part .= "$vmid: Could not open log file\n\n";
        }
-       close (TMP);
        $html_log_part .= "\n";
     }
     $html_log_part .= escape_html($detail_post) if defined($detail_post);
     $html_log_part .= "</pre>";
-    my $html_end .= "\n</body></html>\n";
+    my $html_end = "\n</body></html>\n";
     # end html part
 
     if (length($text) + length($text_log_part) +
-       length($html) + length($html_log_part) < MAX_MAIL_SIZE)
+       length($html) + length($html_log_part) +
+       length($html_end) < MAX_MAIL_SIZE)
     {
        $html .= $html_log_part;
+       $html .= $html_end;
        $text .= $text_log_part;
     } else {
        my $msg = "Log output was too long to be sent by mail. ".
@@ -401,12 +447,8 @@ sub new {
 
     my $defaults = read_vzdump_defaults();
 
-    my $maxfiles = $opts->{maxfiles}; # save here, because we overwrite with default
-
-    $opts->{remove} = 1 if !defined($opts->{remove});
-
     foreach my $k (keys %$defaults) {
-       next if $k eq 'exclude-path'; # dealt with separately
+       next if $k eq 'exclude-path' || $k eq 'prune-backups'; # dealt with separately
        if ($k eq 'dumpdir' || $k eq 'storage') {
            $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
                !defined ($opts->{storage});
@@ -419,7 +461,11 @@ sub new {
     $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
 
     $skiplist = [] if !$skiplist;
-    my $self = bless { cmdline => $cmdline, opts => $opts, skiplist => $skiplist };
+    my $self = bless {
+       cmdline => $cmdline,
+       opts => $opts,
+       skiplist => $skiplist,
+    }, $class;
 
     my $findexcl = $self->{findexcl} = [];
     if ($defaults->{'exclude-path'}) {
@@ -431,20 +477,23 @@ sub new {
     }
 
     if ($opts->{stdexcludes}) {
-       push @$findexcl, '/tmp/?*',
-                        '/var/tmp/?*',
-                        '/var/run/?*.pid';
+       push @$findexcl,
+           '/tmp/?*',
+           '/var/tmp/?*',
+           '/var/run/?*.pid',
+           ;
     }
 
     foreach my $p (@plugins) {
-
-       my $pd = $p->new ($self);
+       my $pd = $p->new($self);
 
        push @{$self->{plugins}}, $pd;
     }
 
     if (defined($opts->{storage}) && $opts->{stdout}) {
-       die "unable to use option 'storage' with option 'stdout'\n";
+       die "cannot use options 'storage' and 'stdout' at the same time\n";
+    } elsif (defined($opts->{storage}) && defined($opts->{dumpdir})) {
+       die "cannot use options 'storage' and 'dumpdir' at the same time\n";
     }
 
     if (!$opts->{dumpdir} && !$opts->{storage}) {
@@ -454,12 +503,23 @@ sub new {
     my $errors = '';
 
     if ($opts->{storage}) {
+       my $storage_cfg = PVE::Storage::config();
+       eval { PVE::Storage::activate_storage($storage_cfg, $opts->{storage}) };
+       if (my $err = $@) {
+           chomp($err);
+           $errors .= "could not activate storage '$opts->{storage}': $err";
+       }
+
        my $info = eval { storage_info ($opts->{storage}) };
-       $errors .= "could not get storage information for '$opts->{storage}': $@"
-           if ($@);
-       $opts->{dumpdir} = $info->{dumpdir};
-       $opts->{scfg} = $info->{scfg};
-       $maxfiles //= $info->{maxfiles};
+       if (my $err = $@) {
+           chomp($err);
+           $errors .= "could not get storage information for '$opts->{storage}': $err";
+       } else {
+           $opts->{dumpdir} = $info->{dumpdir};
+           $opts->{scfg} = $info->{scfg};
+           $opts->{pbs} = $info->{pbs};
+           $opts->{'prune-backups'} //= $info->{'prune-backups'};
+       }
     } elsif ($opts->{dumpdir}) {
        $errors .= "dumpdir '$opts->{dumpdir}' does not exist"
            if ! -d $opts->{dumpdir};
@@ -467,6 +527,11 @@ sub new {
        die "internal error";
     }
 
+    $opts->{'prune-backups'} //= $defaults->{'prune-backups'};
+
+    # avoid triggering any remove code path if keep-all is set
+    $opts->{remove} = 0 if $opts->{'prune-backups'}->{'keep-all'};
+
     if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
        $errors .= "\n" if $errors;
        $errors .= "tmpdir '$opts->{tmpdir}' does not exist";
@@ -478,10 +543,7 @@ sub new {
        die "$errors\n";
     }
 
-    $opts->{maxfiles} = $maxfiles if defined($maxfiles);
-
     return $self;
-
 }
 
 sub get_mount_info {
@@ -518,30 +580,29 @@ sub getlock {
 
     my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
 
-    die "missimg UPID" if !$upid; # should not happen
+    die "missing UPID" if !$upid; # should not happen
 
-    if (!open (SERVER_FLCK, ">>$lockfile")) {
+    my $SERVER_FLCK;
+    if (!open ($SERVER_FLCK, '>>', "$lockfile")) {
        debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
        die "can't open lock on file '$lockfile' - $!";
     }
 
-    if (!flock (SERVER_FLCK, LOCK_EX|LOCK_NB)) {
-
+    if (!flock ($SERVER_FLCK, LOCK_EX|LOCK_NB)) {
        if (!$maxwait) {
            debugmsg ('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
            die "can't acquire lock '$lockfile' (wait = 0)";
        }
 
        debugmsg('info', "trying to get global lock - waiting...", undef, 1);
-
        eval {
            alarm ($maxwait * 60);
 
            local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
 
-           if (!flock (SERVER_FLCK, LOCK_EX)) {
+           if (!flock ($SERVER_FLCK, LOCK_EX)) {
                my $err = $!;
-               close (SERVER_FLCK);
+               close ($SERVER_FLCK);
                alarm (0);
                die "$err\n";
            }
@@ -560,6 +621,8 @@ sub getlock {
     }
 
     PVE::Tools::file_set_contents($pidfile, $upid);
+
+    return $SERVER_FLCK;
 }
 
 sub run_hook_script {
@@ -568,22 +631,29 @@ sub run_hook_script {
     my $opts = $self->{opts};
 
     my $script = $opts->{script};
-
     return if !$script;
 
-    my $cmd = "$script $phase";
+    if (!-x $script) {
+       die "The hook script '$script' is not executable.\n";
+    }
+
+    my $cmd = [$script, $phase];
 
-    $cmd .= " $task->{mode} $task->{vmid}" if ($task);
+    if ($task) {
+       push @$cmd, $task->{mode};
+       push @$cmd, $task->{vmid};
+    }
 
     local %ENV;
-
     # set immutable opts directly (so they are available in all phases)
     $ENV{STOREID} = $opts->{storage} if $opts->{storage};
     $ENV{DUMPDIR} = $opts->{dumpdir} if $opts->{dumpdir};
 
-    foreach my $ek (qw(vmtype hostname tarfile logfile)) {
+    foreach my $ek (qw(vmtype hostname target logfile)) {
        $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
     }
+    # FIXME: for backwards compatibility - drop with PVE 7.0
+    $ENV{TARFILE} = $task->{target} if $task->{target};
 
     run_command ($logfd, $cmd);
 }
@@ -607,6 +677,13 @@ sub compressor_info {
        } else {
            return ('gzip --rsyncable', 'gz');
        }
+    } elsif ($opt_compress eq 'zstd') {
+       my $zstd_threads = $opts->{zstd} // 1;
+       if ($zstd_threads == 0) {
+           my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
+           $zstd_threads = int(($cpuinfo->{cpus} + 1)/2);
+       }
+       return ("zstd --rsyncable --threads=${zstd_threads}", 'zst');
     } else {
        die "internal error - unknown compression option '$opt_compress'";
     }
@@ -618,10 +695,15 @@ sub get_backup_file_list {
     my $bklist = [];
     foreach my $fn (<$dir/${bkname}-*>) {
        next if $exclude_fn && $fn eq $exclude_fn;
-       if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?)))$!) {
-           $fn = "$dir/$1"; # untaint
-           my $t = timelocal ($7, $6, $5, $4, $3 - 1, $2);
-           push @$bklist, [$fn, $t];
+
+       my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
+       if ($archive_info->{is_std_name}) {
+           my $filename = $archive_info->{filename};
+           my $backup = {
+               'path' => "$dir/$filename",
+               'ctime' => $archive_info->{ctime},
+           };
+           push @{$bklist}, $backup;
        }
     }
 
@@ -633,27 +715,15 @@ sub exec_backup_task {
 
     my $opts = $self->{opts};
 
+    my $cfg = PVE::Storage::config();
     my $vmid = $task->{vmid};
     my $plugin = $task->{plugin};
-    my $vmtype = $plugin->type();
 
     $task->{backup_time} = time();
 
     my $pbs_group_name;
     my $pbs_snapshot_name;
 
-    if ($opts->{scfg}->{type} eq 'pbs') {
-       if ($vmtype eq 'lxc') {
-           $pbs_group_name = "ct/$vmid";
-       } elsif  ($vmtype eq 'qemu') {
-           $pbs_group_name = "vm/$vmid";
-       } else {
-           die "pbs backup not implemented for plugin type '$vmtype'\n";
-       }
-       my $btime = strftime("%FT%TZ", gmtime($task->{backup_time}));
-       $pbs_snapshot_name = "$pbs_group_name/$btime";
-    }
-
     my $vmstarttime = time ();
 
     my $logfd;
@@ -664,12 +734,27 @@ sub exec_backup_task {
        return if !defined($task->{vmstoptime});
        $task->{vmconttime} //= time();
        my $delay = $task->{vmconttime} - $task->{vmstoptime};
+       $delay = '<1' if $delay < 1;
        debugmsg ('info', "guest is online again after $delay seconds", $logfd);
     };
 
     eval {
        die "unable to find VM '$vmid'\n" if !$plugin;
 
+       my $vmtype = $plugin->type();
+
+       if ($self->{opts}->{pbs}) {
+           if ($vmtype eq 'lxc') {
+               $pbs_group_name = "ct/$vmid";
+           } elsif  ($vmtype eq 'qemu') {
+               $pbs_group_name = "vm/$vmid";
+           } else {
+               die "pbs backup not implemented for plugin type '$vmtype'\n";
+           }
+           my $btime = strftime("%FT%TZ", gmtime($task->{backup_time}));
+           $pbs_snapshot_name = "$pbs_group_name/$btime";
+       }
+
        # for now we deny backups of a running ha managed service in *stop* mode
        # as it interferes with the HA stack (started services should not stop).
        if ($opts->{mode} eq 'stop' &&
@@ -684,24 +769,31 @@ sub exec_backup_task {
        my $bkname = "vzdump-$vmtype-$vmid";
        my $basename = $bkname . strftime("-%Y_%m_%d-%H_%M_%S", localtime($task->{backup_time}));
 
-       my $maxfiles = $opts->{maxfiles};
+       my $prune_options = $opts->{'prune-backups'};
+
+       my $backup_limit = 0;
+       if (!$prune_options->{'keep-all'}) {
+           foreach my $keep (values %{$prune_options}) {
+               $backup_limit += $keep;
+           }
+       }
 
-       if ($maxfiles && !$opts->{remove}) {
+       if ($backup_limit && !$opts->{remove}) {
            my $count;
-           if ($opts->{scfg}->{type} eq 'pbs') {
+           if ($self->{opts}->{pbs}) {
                my $res = PVE::Storage::PBSPlugin::run_client_cmd($opts->{scfg}, $opts->{storage}, 'snapshots', $pbs_group_name);
                $count = scalar(@$res);
            } else {
                my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
                $count = scalar(@$bklist);
            }
-           die "There is a max backup limit of ($maxfiles) enforced by the".
+           die "There is a max backup limit of $backup_limit enforced by the".
                " target storage or the vzdump parameters.".
                " Either increase the limit or delete old backup(s).\n"
-               if $count >= $maxfiles;
+               if $count >= $backup_limit;
        }
 
-       if ($opts->{scfg}->{type} ne 'pbs') {
+       if (!$self->{opts}->{pbs}) {
            $task->{logfile} = "$opts->{dumpdir}/$basename.log";
        }
 
@@ -711,14 +803,14 @@ sub exec_backup_task {
            $ext .= ".${comp_ext}";
        }
 
-       if ($opts->{scfg}->{type} eq 'pbs') {
+       if ($self->{opts}->{pbs}) {
            die "unable to pipe backup to stdout\n" if $opts->{stdout};
+           $task->{target} = $pbs_snapshot_name;
        } else {
            if ($opts->{stdout}) {
-               $task->{tarfile} = '-';
+               $task->{target} = '-';
            } else {
-               my $tarfile = $task->{tarfile} = "$opts->{dumpdir}/$basename$ext";
-               $task->{tmptar} = $task->{tarfile};
+               $task->{target} = $task->{tmptar} = "$opts->{dumpdir}/$basename$ext";
                $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
                unlink $task->{tmptar};
            }
@@ -726,10 +818,11 @@ sub exec_backup_task {
 
        $task->{vmtype} = $vmtype;
 
-       if ($opts->{scfg}->{type} eq 'pbs') {
-           $task->{tmpdir} = "/var/tmp/vzdumptmp$$"; #fixme
-       } elsif ($opts->{tmpdir}) {
-           $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp$$";
+       my $pid = $$;
+       if ($opts->{tmpdir}) {
+           $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp${pid}_$vmid/";
+       } elsif ($self->{opts}->{pbs}) {
+           $task->{tmpdir} = "/var/tmp/vzdumptmp${pid}_$vmid";
        } else {
            # dumpdir is posix? then use it as temporary dir
            my $info = get_mount_info($opts->{dumpdir});
@@ -737,7 +830,7 @@ sub exec_backup_task {
                grep ($_ eq $info->{fstype}, @posix_filesystems)) {
                $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
            } else {
-               $task->{tmpdir} = "/var/tmp/vzdumptmp$$";
+               $task->{tmpdir} = "/var/tmp/vzdumptmp${pid}_$vmid";
                debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
                          "using $task->{tmpdir} for temporary files", $logfd);
            }
@@ -826,7 +919,7 @@ sub exec_backup_task {
                $plugin->copy_data_phase1($task, $vmid);
            }
 
-           debugmsg ('info', "suspend vm", $logfd);
+           debugmsg ('info', "suspending guest", $logfd);
            $task->{vmstoptime} = time ();
            $self->run_hook_script ('pre-stop', $task, $logfd);
            $plugin->suspend_vm ($task, $vmid);
@@ -836,7 +929,7 @@ sub exec_backup_task {
                # post-suspend rsync
                $plugin->copy_data_phase2($task, $vmid);
 
-               debugmsg ('info', "resume vm", $logfd);
+               debugmsg ('info', "resuming guest", $logfd);
                $cleanup->{resume} = 0;
                $self->run_hook_script('pre-restart', $task, $logfd);
                $plugin->resume_vm($task, $vmid);
@@ -888,47 +981,38 @@ sub exec_backup_task {
            return;
        }
 
-       # fixme: ??
-       if ($opts->{scfg}->{type} eq 'pbs') {
-           debugmsg ('info', "creating pbs archive on storage '$opts->{storage}'", $logfd);
-       } else {
-           debugmsg ('info', "creating archive '$task->{tarfile}'", $logfd);
-       }
+       my $archive_txt = $self->{opts}->{pbs} ? 'Proxmox Backup Server' : 'vzdump';
+       debugmsg('info', "creating $archive_txt archive '$task->{target}'", $logfd);
        $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
 
-       if ($opts->{scfg}->{type} eq 'pbs') {
-           # fixme: log size ?
-           debugmsg ('info', "pbs upload finished", $logfd);
+       if ($self->{opts}->{pbs}) {
+           # size is added to task struct in guest vzdump plugins
        } else {
-           rename ($task->{tmptar}, $task->{tarfile}) ||
-               die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
+           rename ($task->{tmptar}, $task->{target}) ||
+               die "unable to rename '$task->{tmptar}' to '$task->{target}'\n";
 
            # determine size
-           $task->{size} = (-s $task->{tarfile}) || 0;
+           $task->{size} = (-s $task->{target}) || 0;
            my $cs = format_size ($task->{size});
            debugmsg ('info', "archive file size: $cs", $logfd);
        }
 
        # purge older backup
-       if ($maxfiles && $opts->{remove}) {
+       if ($opts->{remove}) {
+           if (!defined($opts->{storage})) {
+               my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname, $task->{target});
+               PVE::Storage::prune_mark_backup_group($bklist, $prune_options);
 
-           if ($opts->{scfg}->{type} eq 'pbs') {
-               my $args = [$pbs_group_name, '--keep-last', $maxfiles];
-               my $logfunc = sub { my $line = shift; debugmsg ('info', $line, $logfd); };
-               PVE::Storage::PBSPlugin::run_raw_client_cmd(
-                   $opts->{scfg}, $opts->{storage}, 'prune', $args, logfunc => $logfunc);
-           } else {
-               my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname, $task->{tarfile});
-               $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
-
-               while (scalar (@$bklist) >= $maxfiles) {
-                   my $d = pop @$bklist;
-                   debugmsg ('info', "delete old backup '$d->[0]'", $logfd);
-                   unlink $d->[0];
-                   my $logfn = $d->[0];
-                   $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
-                   unlink $logfn;
+               foreach my $prune_entry (@{$bklist}) {
+                   next if $prune_entry->{mark} ne 'remove';
+
+                   my $archive_path = $prune_entry->{path};
+                   debugmsg ('info', "delete old backup '$archive_path'", $logfd);
+                   PVE::Storage::archive_remove($archive_path);
                }
+           } else {
+               my $logfunc = sub { debugmsg($_[0], $_[1], $logfd) };
+               PVE::Storage::prune_backups($cfg, $opts->{storage}, $prune_options, $vmid, $vmtype, 0, $logfunc);
            }
        }
 
@@ -1003,11 +1087,18 @@ sub exec_backup_task {
     close ($logfd) if $logfd;
 
     if ($task->{tmplog}) {
-       if ($opts->{scfg}->{type} eq 'pbs') {
+       if ($self->{opts}->{pbs}) {
            if ($task->{state} eq 'ok') {
-               my $param = [$pbs_snapshot_name, $task->{tmplog}];
-               PVE::Storage::PBSPlugin::run_raw_client_cmd(
-                   $opts->{scfg}, $opts->{storage}, 'upload-log', $param, errmsg => "upload log failed");
+               eval {
+                   PVE::Storage::PBSPlugin::run_raw_client_cmd(
+                       $opts->{scfg},
+                       $opts->{storage},
+                       'upload-log',
+                       [ $pbs_snapshot_name, $task->{tmplog} ],
+                       errmsg => "uploading backup task log failed",
+                   );
+               };
+               debugmsg('warn', "$@") if $@; # $@ contains already error prefix
            }
        } elsif ($task->{logfile}) {
            system {'cp'} 'cp', $task->{tmplog}, $task->{logfile};
@@ -1025,33 +1116,35 @@ sub exec_backup {
     my $opts = $self->{opts};
 
     debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
-    debugmsg ('info', "skip external VMs: " . join(', ', @{$self->{skiplist}}))
-       if scalar(@{$self->{skiplist}});
+
+    if (scalar(@{$self->{skiplist}})) {
+       my $skip_string = join(', ', sort { $a <=> $b } @{$self->{skiplist}});
+       debugmsg ('info', "skip external VMs: $skip_string");
+    }
 
     my $tasklist = [];
+    my $vzdump_plugins =  {};
+    foreach my $plugin (@{$self->{plugins}}) {
+       my $type = $plugin->type();
+       next if exists $vzdump_plugins->{$type};
+       $vzdump_plugins->{$type} = $plugin;
+    }
 
-    if ($opts->{all}) {
-       foreach my $plugin (@{$self->{plugins}}) {
-           my $vmlist = $plugin->vmlist();
-           foreach my $vmid (sort @$vmlist) {
-               next if grep { $_ eq  $vmid } @{$opts->{exclude}};
-               next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
-               push @$tasklist, { vmid => $vmid,  state => 'todo', plugin => $plugin, mode => $opts->{mode} };
-           }
-       }
-    } else {
-       foreach my $vmid (sort @{$opts->{vmids}}) {
-           my $plugin;
-           foreach my $pg (@{$self->{plugins}}) {
-               my $vmlist = $pg->vmlist();
-               if (grep { $_ eq  $vmid } @$vmlist) {
-                   $plugin = $pg;
-                   last;
-               }
-           }
-           $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
-           push @$tasklist, { vmid => $vmid,  state => 'todo', plugin => $plugin, mode => $opts->{mode} };
+    my $vmlist = PVE::Cluster::get_vmlist();
+    my $vmids = [ sort { $a <=> $b } @{$opts->{vmids}} ];
+    foreach my $vmid (@{$vmids}) {
+       my $plugin;
+       if (defined($vmlist->{ids}->{$vmid})) {
+           my $guest_type = $vmlist->{ids}->{$vmid}->{type};
+           $plugin = $vzdump_plugins->{$guest_type};
+           next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], $opts->{all});
        }
+       push @$tasklist, {
+           mode => $opts->{mode},
+           plugin => $plugin,
+           state => 'todo',
+           vmid => $vmid,
+       };
     }
 
     # Use in-memory files for the outer hook logs to pass them to sendmail.
@@ -1108,6 +1201,27 @@ sub option_exists {
     return defined($confdesc->{$key});
 }
 
+# NOTE it might make sense to merge this and verify_vzdump_parameters(), but one
+# needs to adapt command_line() in guest-common's PVE/VZDump/Common.pm and detect
+# a second parsing attempt, because verify_vzdump_parameters() is called twice
+# during the update_job API call.
+sub parse_mailto_exclude_path {
+    my ($param) = @_;
+
+    # exclude-path list need to be 0 separated
+    if (defined($param->{'exclude-path'})) {
+       my @expaths = split(/\0/, $param->{'exclude-path'} || '');
+       $param->{'exclude-path'} = [ @expaths ];
+    }
+
+    if (defined($param->{mailto})) {
+       my @mailto = PVE::Tools::split_list(extract_param($param, 'mailto'));
+       $param->{mailto} = [ @mailto ];
+    }
+
+    return;
+}
+
 sub verify_vzdump_parameters {
     my ($param, $check_missing) = @_;
 
@@ -1120,11 +1234,12 @@ sub verify_vzdump_parameters {
     raise_param_exc({ pool => "option conflicts with option 'vmid'"})
        if $param->{pool} && $param->{vmid};
 
-    $param->{all} = 1 if (defined($param->{exclude}) && !$param->{pool});
+    raise_param_exc({ 'prune-backups' => "option conflicts with option 'maxfiles'"})
+       if defined($param->{'prune-backups'}) && defined($param->{maxfiles});
+
+    $parse_prune_backups_maxfiles->($param, 'CLI parameters');
 
-    warn "option 'size' is deprecated and will be removed in a future " .
-        "release, please update your script/configuration!\n"
-       if defined($param->{size});
+    $param->{all} = 1 if (defined($param->{exclude}) && !$param->{pool});
 
     return if !$check_missing;
 
@@ -1154,4 +1269,44 @@ sub stop_running_backups {
     }
 }
 
+sub get_included_guests {
+    my ($job) = @_;
+
+    my $vmids = [];
+    my $vmids_per_node = {};
+
+    my $vmlist = PVE::Cluster::get_vmlist();
+
+    if ($job->{pool}) {
+       $vmids = PVE::API2Tools::get_resource_pool_guest_members($job->{pool});
+    } elsif ($job->{vmid}) {
+       $vmids = [ split_list($job->{vmid}) ];
+    } elsif ($job->{all}) {
+       # all or exclude
+       my $exclude = check_vmids(split_list($job->{exclude}));
+       my $excludehash = { map { $_ => 1 } @$exclude };
+
+       for my $id (keys %{$vmlist->{ids}}) {
+           next if $excludehash->{$id};
+           push @$vmids, $id;
+       }
+    } else {
+       return $vmids_per_node;
+    }
+    $vmids = check_vmids(@$vmids);
+
+    for my $vmid (@$vmids) {
+       if (defined($vmlist->{ids}->{$vmid})) {
+           my $node = $vmlist->{ids}->{$vmid}->{node};
+           next if (defined $job->{node} && $job->{node} ne $node);
+
+           push @{$vmids_per_node->{$node}}, $vmid;
+       } else {
+           push @{$vmids_per_node->{''}}, $vmid;
+       }
+    }
+
+    return $vmids_per_node;
+}
+
 1;