13 use POSIX
qw(strftime);
16 use PVE
::Cluster
qw(cfs_read_file);
17 use PVE
::DataCenterConfig
;
18 use PVE
::Exception
qw(raise_param_exc);
20 use PVE
::HA
::Env
::PVE2
;
21 use PVE
::JSONSchema
qw(get_standard_option);
22 use PVE
::RPCEnvironment
;
24 use PVE
::VZDump
::Common
;
25 use PVE
::VZDump
::Plugin
;
26 use PVE
::Tools
qw(extract_param split_list);
29 my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
31 my $lockfile = '/var/run/vzdump.lock';
32 my $pidfile = '/var/run/vzdump.pid';
33 my $logdir = '/var/log/vzdump';
37 my $confdesc = PVE
::VZDump
::Common
::get_confdesc
();
39 my $confdesc_for_defaults = Clone
::clone
($confdesc);
40 delete $confdesc_for_defaults->{$_}->{requires
} for qw(notes-template protected);
42 # Load available plugins
43 my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
44 foreach my $plug (@pve_vzdump_classes) {
45 my $filename = "/usr/share/perl5/$plug.pm";
46 $filename =~ s!::!/!g;
48 eval { require $filename; };
61 my ($mtype, $msg, $logfd, $syslog) = @_;
63 PVE
::VZDump
::Plugin
::debugmsg
(@_);
67 my ($logfd, $cmdstr, %param) = @_;
71 debugmsg
('info', $line, $logfd);
74 PVE
::Tools
::run_command
($cmdstr, %param, logfunc
=> $logfunc);
77 my $verify_notes_template = sub {
80 die "contains a line feed\n" if $template =~ /\n/;
83 while ($template =~ /\\(.)/g) {
85 push @problematic, "escape sequence '\\$char' at char " . (pos($template) - 2)
86 if $char !~ /^[n\\]$/;
89 while ($template =~ /\{\{([^\s{}]+)\}\}/g) {
91 push @problematic, "variable '$var' at char " . (pos($template) - length($var))
92 if $var !~ /^(cluster|guestname|node|vmid)$/;
95 die "found unknown: " . join(', ', @problematic) . "\n" if scalar(@problematic);
98 my $generate_notes = sub {
99 my ($notes_template, $task) = @_;
101 $verify_notes_template->($notes_template);
104 cluster
=> PVE
::Cluster
::get_clinfo
()->{cluster
}->{name
} // 'standalone node',
105 guestname
=> $task->{hostname
} // "VM $task->{vmid}", # is always set for CTs
106 node
=> PVE
::INotify
::nodename
(),
107 vmid
=> $task->{vmid
},
112 return '\\' if $char eq '\\';
113 return "\n" if $char eq 'n';
114 die "unexpected escape character '$char'\n";
117 $notes_template =~ s/\\(.)/$unescape->($1)/eg;
119 my $vars = join('|', keys $info->%*);
120 $notes_template =~ s/\{\{($vars)\}\}/$info->{$1}/g;
122 return $notes_template;
125 my sub parse_performance
{
128 if (defined(my $perf = $param->{performance
})) {
129 return if ref($perf) eq 'HASH'; # already parsed
130 $param->{performance
} = PVE
::JSONSchema
::parse_property_string
('backup-performance', $perf);
134 my $parse_prune_backups_maxfiles = sub {
135 my ($param, $kind) = @_;
137 my $maxfiles = delete $param->{maxfiles
};
138 my $prune_backups = $param->{'prune-backups'};
140 debugmsg
('warn', "both 'maxfiles' and 'prune-backups' defined as ${kind} - ignoring 'maxfiles'")
141 if defined($maxfiles) && defined($prune_backups);
143 if (defined($prune_backups)) {
144 return if ref($prune_backups) eq 'HASH'; # already parsed
145 $param->{'prune-backups'} = PVE
::JSONSchema
::parse_property_string
(
149 } elsif (defined($maxfiles)) {
151 $param->{'prune-backups'} = { 'keep-last' => $maxfiles };
153 $param->{'prune-backups'} = { 'keep-all' => 1 };
161 my $cfg = PVE
::Storage
::config
();
162 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
163 my $type = $scfg->{type
};
165 die "can't use storage '$storage' for backups - wrong content type\n"
166 if (!$scfg->{content
}->{backup
});
172 $info->{'prune-backups'} = PVE
::JSONSchema
::parse_property_string
('prune-backups', $scfg->{'prune-backups'})
173 if defined($scfg->{'prune-backups'});
175 if ($type eq 'pbs') {
178 $info->{dumpdir
} = PVE
::Storage
::get_backup_dir
($cfg, $storage);
187 my $kb = $size / 1024;
190 return int ($kb) . "KB";
193 my $mb = $size / (1024*1024);
195 return int ($mb) . "MB";
199 return sprintf ("%.2fGB", $gb);
202 return sprintf ("%.2fTB", $tb);
208 my $hours = int ($seconds/3600);
209 $seconds = $seconds - $hours*3600;
210 my $min = int ($seconds/60);
211 $seconds = $seconds - $min*60;
213 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
219 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
237 foreach my $p (split (/:/, $ENV{PATH
})) {
244 die "unable to find command '$bin'\n";
251 for my $vmid (sort {$a <=> $b} @vmids) {
252 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
253 $vmid = int ($vmid); # remove leading zeros
262 sub read_vzdump_defaults
{
264 my $fn = "/etc/vzdump.conf";
268 my $default = $confdesc->{$_}->{default};
269 defined($default) ?
($_ => $default) : ()
270 } keys %$confdesc_for_defaults
272 $parse_prune_backups_maxfiles->($defaults, "defaults in VZDump schema");
273 parse_performance
($defaults);
276 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
277 return $defaults if $@;
279 my $conf_schema = { type
=> 'object', properties
=> $confdesc_for_defaults };
280 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
281 if (my $excludes = $res->{'exclude-path'}) {
282 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
284 if (defined($res->{mailto
})) {
285 my @mailto = split_list
($res->{mailto
});
286 $res->{mailto
} = [ @mailto ];
288 $parse_prune_backups_maxfiles->($res, "options in '$fn'");
289 parse_performance
($res);
291 foreach my $key (keys %$defaults) {
292 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
295 if (defined($res->{storage
}) && defined($res->{dumpdir
})) {
296 debugmsg
('warn', "both 'storage' and 'dumpdir' defined in '$fn' - ignoring 'dumpdir'");
297 delete $res->{dumpdir
};
303 use constant MAX_MAIL_SIZE
=> 1024*1024;
305 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
307 my $opts = $self->{opts
};
309 my $mailto = $opts->{mailto
};
311 return if !($mailto && scalar(@$mailto));
313 my $cmdline = $self->{cmdline
};
316 foreach my $task (@$tasklist) {
317 $ecount++ if $task->{state} ne 'ok';
318 chomp $task->{msg
} if $task->{msg
};
319 $task->{backuptime
} = 0 if !$task->{backuptime
};
320 $task->{size
} = 0 if !$task->{size
};
321 $task->{target
} = 'unknown' if !$task->{target
};
322 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
324 if ($task->{state} eq 'todo') {
325 $task->{msg
} = 'aborted';
329 my $notify = $opts->{mailnotification
} || 'always';
330 return if (!$ecount && !$err && ($notify eq 'failure'));
332 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
335 $stat .= ": multiple problems";
342 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
346 my $text = $err ?
"$err\n\n" : '';
349 "%-10s %-${namelength}s %-6s %10s %10s %s\n",
350 qw(VMID NAME STATUS TIME SIZE FILENAME)
352 foreach my $task (@$tasklist) {
353 my $name = substr($task->{hostname
}, 0, $namelength);
354 my $successful = $task->{state} eq 'ok';
355 my $size = $successful ? format_size
($task->{size
}) : 0;
356 my $filename = $successful ?
$task->{target
} : '-';
357 my $size_fmt = $successful ?
"%10s": "%8.2fMB";
359 "%-10s %-${namelength}s %-6s %10s $size_fmt %s\n",
363 format_time
($task->{backuptime
}),
370 $text_log_part .= "\nDetailed backup logs:\n\n";
371 $text_log_part .= "$cmdline\n\n";
373 $text_log_part .= $detail_pre . "\n" if defined($detail_pre);
374 foreach my $task (@$tasklist) {
375 my $vmid = $task->{vmid
};
376 my $log = $task->{tmplog
};
378 $text_log_part .= "$vmid: no log available\n\n";
381 if (open (my $TMP, '<', "$log")) {
382 while (my $line = <$TMP>) {
383 next if $line =~ /^status: \d+/; # not useful in mails
384 $text_log_part .= encode8bit
("$vmid: $line");
388 $text_log_part .= "$vmid: Could not open log file\n\n";
390 $text_log_part .= "\n";
392 $text_log_part .= $detail_post if defined($detail_post);
395 my $html = "<html><body>\n";
396 $html .= "<p>" . (escape_html
($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
397 $html .= "<table border=1 cellpadding=3>\n";
398 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
401 foreach my $task (@$tasklist) {
402 my $vmid = $task->{vmid
};
403 my $name = $task->{hostname
};
405 if ($task->{state} eq 'ok') {
406 $ssize += $task->{size
};
409 "<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
412 format_time
($task->{backuptime
}),
413 format_size
($task->{size
}),
414 escape_html
($task->{target
}),
418 "<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
421 format_time
($task->{backuptime
}),
422 escape_html
($task->{msg
}),
427 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
428 format_time
($totaltime), format_size
($ssize));
430 $html .= "\n</table><br><br>\n";
432 $html_log_part .= "Detailed backup logs:<br /><br />\n";
433 $html_log_part .= "<pre>\n";
434 $html_log_part .= escape_html
($cmdline) . "\n\n";
436 $html_log_part .= escape_html
($detail_pre) . "\n" if defined($detail_pre);
437 foreach my $task (@$tasklist) {
438 my $vmid = $task->{vmid
};
439 my $log = $task->{tmplog
};
441 $html_log_part .= "$vmid: no log available\n\n";
444 if (open (my $TMP, '<', "$log")) {
445 while (my $line = <$TMP>) {
446 next if $line =~ /^status: \d+/; # not useful in mails
447 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
448 $html_log_part .= encode8bit
("$vmid: <font color=red>".
449 escape_html
($line) . "</font>");
451 $html_log_part .= encode8bit
("$vmid: " . escape_html
($line));
456 $html_log_part .= "$vmid: Could not open log file\n\n";
458 $html_log_part .= "\n";
460 $html_log_part .= escape_html
($detail_post) if defined($detail_post);
461 $html_log_part .= "</pre>";
462 my $html_end = "\n</body></html>\n";
465 if (length($text) + length($text_log_part) +
466 length($html) + length($html_log_part) +
467 length($html_end) < MAX_MAIL_SIZE
)
469 $html .= $html_log_part;
471 $text .= $text_log_part;
473 my $msg = "Log output was too long to be sent by mail. ".
474 "See Task History for details!\n";
476 $html .= "<p>$msg</p>";
480 my $subject = "vzdump backup status ($hostname) : $stat";
482 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
483 my $mailfrom = $dcconf->{email_from
} || "root";
485 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
489 my ($class, $cmdline, $opts, $skiplist) = @_;
495 check_bin
('sendmail');
499 check_bin
('umount');
500 check_bin
('cstream');
501 check_bin
('ionice');
503 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
504 check_bin
('lvcreate');
506 check_bin
('lvremove');
509 my $defaults = read_vzdump_defaults
();
511 foreach my $k (keys %$defaults) {
512 next if $k eq 'exclude-path' || $k eq 'prune-backups'; # dealt with separately
513 if ($k eq 'dumpdir' || $k eq 'storage') {
514 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
515 !defined ($opts->{storage
});
517 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
521 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
522 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
524 $skiplist = [] if !$skiplist;
528 skiplist
=> $skiplist,
531 my $findexcl = $self->{findexcl
} = [];
532 if ($defaults->{'exclude-path'}) {
533 push @$findexcl, @{$defaults->{'exclude-path'}};
536 if ($opts->{'exclude-path'}) {
537 push @$findexcl, @{$opts->{'exclude-path'}};
540 if ($opts->{stdexcludes
}) {
548 foreach my $p (@plugins) {
549 my $pd = $p->new($self);
551 push @{$self->{plugins
}}, $pd;
554 if (defined($opts->{storage
}) && $opts->{stdout
}) {
555 die "cannot use options 'storage' and 'stdout' at the same time\n";
556 } elsif (defined($opts->{storage
}) && defined($opts->{dumpdir
})) {
557 die "cannot use options 'storage' and 'dumpdir' at the same time\n";
560 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
561 $opts->{storage
} = 'local';
564 # Enforced by the API too, but these options might come in via defaults. Drop them if necessary.
565 if (!$opts->{storage
}) {
566 delete $opts->{$_} for qw(notes-template protected);
570 my $add_error = sub {
572 $errors .= "\n" if $errors;
578 $self->{job_init_log
} = '';
579 open my $job_init_fd, '>', \
$self->{job_init_log
};
580 $self->run_hook_script('job-init', undef, $job_init_fd);
583 PVE
::Cluster
::cfs_update
(); # Pick up possible changes made by the hook script.
585 $add_error->($@) if $@;
587 if ($opts->{storage
}) {
588 my $storage_cfg = PVE
::Storage
::config
();
589 eval { PVE
::Storage
::activate_storage
($storage_cfg, $opts->{storage
}) };
590 $add_error->("could not activate storage '$opts->{storage}': $@") if $@;
592 my $info = eval { storage_info
($opts->{storage
}) };
594 $add_error->("could not get storage information for '$opts->{storage}': $err");
596 $opts->{dumpdir
} = $info->{dumpdir
};
597 $opts->{scfg
} = $info->{scfg
};
598 $opts->{pbs
} = $info->{pbs
};
599 $opts->{'prune-backups'} //= $info->{'prune-backups'};
601 } elsif ($opts->{dumpdir
}) {
602 $add_error->("dumpdir '$opts->{dumpdir}' does not exist")
603 if ! -d
$opts->{dumpdir
};
605 die "internal error";
608 $opts->{'prune-backups'} //= $defaults->{'prune-backups'};
610 # avoid triggering any remove code path if keep-all is set
611 $opts->{remove
} = 0 if $opts->{'prune-backups'}->{'keep-all'};
613 if ($opts->{tmpdir
} && ! -d
$opts->{tmpdir
}) {
614 $add_error->("tmpdir '$opts->{tmpdir}' does not exist");
618 eval { $self->sendmail([], 0, $errors); };
619 debugmsg
('err', $@) if $@;
629 # Note: df 'available' can be negative, and percentage set to '-'
631 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
637 if (my ($fsid, $fstype, undef, $mp) = $line =~
638 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
647 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
654 my ($self, $upid) = @_;
658 my $maxwait = $self->{opts
}->{lockwait
} || $self->{lockwait
};
660 die "missing UPID" if !$upid; # should not happen
663 if (!open ($SERVER_FLCK, '>>', "$lockfile")) {
664 debugmsg
('err', "can't open lock on file '$lockfile' - $!", undef, 1);
665 die "can't open lock on file '$lockfile' - $!";
668 if (!flock ($SERVER_FLCK, LOCK_EX
|LOCK_NB
)) {
670 debugmsg
('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
671 die "can't acquire lock '$lockfile' (wait = 0)";
674 debugmsg
('info', "trying to get global lock - waiting...", undef, 1);
676 alarm ($maxwait * 60);
678 local $SIG{ALRM
} = sub { alarm (0); die "got timeout\n"; };
680 if (!flock ($SERVER_FLCK, LOCK_EX
)) {
682 close ($SERVER_FLCK);
693 debugmsg
('err', "can't acquire lock '$lockfile' - $err", undef, 1);
694 die "can't acquire lock '$lockfile' - $err";
697 debugmsg
('info', "got global lock", undef, 1);
700 PVE
::Tools
::file_set_contents
($pidfile, $upid);
705 sub run_hook_script
{
706 my ($self, $phase, $task, $logfd) = @_;
708 my $opts = $self->{opts
};
710 my $script = $opts->{script
};
713 die "Error: The hook script '$script' does not exist.\n" if ! -f
$script;
714 die "Error: The hook script '$script' is not executable.\n" if ! -x
$script;
716 my $cmd = [$script, $phase];
719 push @$cmd, $task->{mode
};
720 push @$cmd, $task->{vmid
};
724 # set immutable opts directly (so they are available in all phases)
725 $ENV{STOREID
} = $opts->{storage
} if $opts->{storage
};
726 $ENV{DUMPDIR
} = $opts->{dumpdir
} if $opts->{dumpdir
};
728 foreach my $ek (qw(vmtype hostname target logfile)) {
729 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
732 run_command
($logfd, $cmd);
735 sub compressor_info
{
737 my $opt_compress = $opts->{compress
};
739 if (!$opt_compress || $opt_compress eq '0') {
741 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
742 return ('lzop', 'lzo');
743 } elsif ($opt_compress eq 'gzip') {
744 if ($opts->{pigz
} > 0) {
745 my $pigz_threads = $opts->{pigz
};
746 if ($pigz_threads == 1) {
747 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
748 $pigz_threads = int(($cpuinfo->{cpus
} + 1)/2);
750 return ("pigz -p ${pigz_threads} --rsyncable", 'gz');
752 return ('gzip --rsyncable', 'gz');
754 } elsif ($opt_compress eq 'zstd') {
755 my $zstd_threads = $opts->{zstd
} // 1;
756 if ($zstd_threads == 0) {
757 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
758 $zstd_threads = int(($cpuinfo->{cpus
} + 1)/2);
760 return ("zstd --rsyncable --threads=${zstd_threads}", 'zst');
762 die "internal error - unknown compression option '$opt_compress'";
766 sub get_backup_file_list
{
767 my ($dir, $bkname) = @_;
770 foreach my $fn (<$dir/${bkname
}-*>) {
771 my $archive_info = eval { PVE
::Storage
::archive_info
($fn) } // {};
772 if ($archive_info->{is_std_name
}) {
773 my $path = "$dir/$archive_info->{filename}";
776 'ctime' => $archive_info->{ctime
},
778 $backup->{mark
} = "protected"
779 if -e PVE
::Storage
::protection_file_path
($path);
780 push @{$bklist}, $backup;
787 sub exec_backup_task
{
788 my ($self, $task) = @_;
790 my $opts = $self->{opts
};
792 my $cfg = PVE
::Storage
::config
();
793 my $vmid = $task->{vmid
};
794 my $plugin = $task->{plugin
};
796 $task->{backup_time
} = time();
799 my $pbs_snapshot_name;
801 my $vmstarttime = time ();
807 my $log_vm_online_again = sub {
808 return if !defined($task->{vmstoptime
});
809 $task->{vmconttime
} //= time();
810 my $delay = $task->{vmconttime
} - $task->{vmstoptime
};
811 $delay = '<1' if $delay < 1;
812 debugmsg
('info', "guest is online again after $delay seconds", $logfd);
816 die "unable to find VM '$vmid'\n" if !$plugin;
818 my $vmtype = $plugin->type();
820 if ($self->{opts
}->{pbs
}) {
821 if ($vmtype eq 'lxc') {
822 $pbs_group_name = "ct/$vmid";
823 } elsif ($vmtype eq 'qemu') {
824 $pbs_group_name = "vm/$vmid";
826 die "pbs backup not implemented for plugin type '$vmtype'\n";
828 my $btime = strftime
("%FT%TZ", gmtime($task->{backup_time
}));
829 $pbs_snapshot_name = "$pbs_group_name/$btime";
832 # for now we deny backups of a running ha managed service in *stop* mode
833 # as it interferes with the HA stack (started services should not stop).
834 if ($opts->{mode
} eq 'stop' &&
835 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'started'))
837 die "Cannot execute a backup with stop mode on a HA managed and".
838 " enabled Service. Use snapshot mode or disable the Service.\n";
841 my $tmplog = "$logdir/$vmtype-$vmid.log";
843 my $bkname = "vzdump-$vmtype-$vmid";
844 my $basename = $bkname . strftime
("-%Y_%m_%d-%H_%M_%S", localtime($task->{backup_time
}));
846 my $prune_options = $opts->{'prune-backups'};
848 my $backup_limit = 0;
849 if (!$prune_options->{'keep-all'}) {
850 foreach my $keep (values %{$prune_options}) {
851 $backup_limit += $keep;
855 if (($backup_limit && !$opts->{remove
}) || $opts->{protected
}) {
858 if (my $storeid = $opts->{storage
}) {
860 !$_->{subtype
} || $_->{subtype
} eq $vmtype
861 } PVE
::Storage
::volume_list
($cfg, $storeid, $vmid, 'backup')->@*;
863 $count = grep { !$_->{protected
} } @backups;
864 $protected_count = scalar(@backups) - $count;
866 $count = grep { !$_->{mark
} || $_->{mark
} ne "protected" } get_backup_file_list
($opts->{dumpdir
}, $bkname)->@*;
869 if ($opts->{protected
}) {
870 my $max_protected = PVE
::Storage
::get_max_protected_backups
(
874 if ($max_protected > -1 && $protected_count >= $max_protected) {
875 die "The number of protected backups per guest is limited to $max_protected ".
876 "on storage '$opts->{storage}'\n";
878 } elsif ($count >= $backup_limit) {
879 die "There is a max backup limit of $backup_limit enforced by the target storage ".
880 "or the vzdump parameters. Either increase the limit or delete old backups.\n";
884 if (!$self->{opts
}->{pbs
}) {
885 $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
888 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
889 my ($comp, $comp_ext) = compressor_info
($opts);
890 if ($comp && $comp_ext) {
891 $ext .= ".${comp_ext}";
894 if ($self->{opts
}->{pbs
}) {
895 die "unable to pipe backup to stdout\n" if $opts->{stdout
};
896 $task->{target
} = $pbs_snapshot_name;
898 if ($opts->{stdout
}) {
899 $task->{target
} = '-';
901 $task->{target
} = $task->{tmptar
} = "$opts->{dumpdir}/$basename$ext";
902 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
903 unlink $task->{tmptar
};
907 $task->{vmtype
} = $vmtype;
910 if ($opts->{tmpdir
}) {
911 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp${pid}_$vmid/";
912 } elsif ($self->{opts
}->{pbs
}) {
913 $task->{tmpdir
} = "/var/tmp/vzdumptmp${pid}_$vmid";
915 # dumpdir is posix? then use it as temporary dir
916 my $info = get_mount_info
($opts->{dumpdir
});
917 if ($vmtype eq 'qemu' ||
918 grep ($_ eq $info->{fstype
}, @posix_filesystems)) {
919 $task->{tmpdir
} = "$opts->{dumpdir}/$basename.tmp";
921 $task->{tmpdir
} = "/var/tmp/vzdumptmp${pid}_$vmid";
922 debugmsg
('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
923 "using $task->{tmpdir} for temporary files", $logfd);
927 rmtree
$task->{tmpdir
};
928 mkdir $task->{tmpdir
};
929 -d
$task->{tmpdir
} ||
930 die "unable to create temporary directory '$task->{tmpdir}'";
932 $logfd = IO
::File-
>new (">$tmplog") ||
933 die "unable to create log file '$tmplog'";
935 $task->{dumpdir
} = $opts->{dumpdir
};
936 $task->{storeid
} = $opts->{storage
};
937 $task->{scfg
} = $opts->{scfg
};
938 $task->{tmplog
} = $tmplog;
940 unlink $task->{logfile
} if defined($task->{logfile
});
942 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
943 debugmsg
('info', "Backup started at " . strftime
("%F %H:%M:%S", localtime()));
945 $plugin->set_logfd ($logfd);
947 # test is VM is running
948 my ($running, $status_text) = $plugin->vm_status ($vmid);
950 debugmsg
('info', "status = ${status_text}", $logfd);
952 # lock VM (prevent config changes)
953 $plugin->lock_vm ($vmid);
955 $cleanup->{unlock
} = 1;
959 my $mode = $running ?
$task->{mode
} : 'stop';
961 if ($mode eq 'snapshot') {
962 my %saved_task = %$task;
963 eval { $plugin->prepare ($task, $vmid, $mode); };
965 die $err if $err !~ m/^mode failure/;
966 debugmsg
('info', $err, $logfd);
967 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
968 $mode = 'suspend'; # so prepare is called again below
969 %$task = %saved_task;
973 $cleanup->{prepared
} = 1;
975 $task->{mode
} = $mode;
977 debugmsg
('info', "backup mode: $mode", $logfd);
978 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd) if $opts->{bwlimit
};
979 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
981 if ($mode eq 'stop') {
982 $plugin->prepare ($task, $vmid, $mode);
984 $self->run_hook_script ('backup-start', $task, $logfd);
987 debugmsg
('info', "stopping virtual guest", $logfd);
988 $task->{vmstoptime
} = time();
989 $self->run_hook_script ('pre-stop', $task, $logfd);
990 $plugin->stop_vm ($task, $vmid);
991 $cleanup->{restart
} = 1;
995 } elsif ($mode eq 'suspend') {
996 $plugin->prepare ($task, $vmid, $mode);
998 $self->run_hook_script ('backup-start', $task, $logfd);
1000 if ($vmtype eq 'lxc') {
1002 $plugin->copy_data_phase1($task, $vmid);
1005 debugmsg
('info', "suspending guest", $logfd);
1006 $task->{vmstoptime
} = time ();
1007 $self->run_hook_script ('pre-stop', $task, $logfd);
1008 $plugin->suspend_vm ($task, $vmid);
1009 $cleanup->{resume
} = 1;
1011 if ($vmtype eq 'lxc') {
1012 # post-suspend rsync
1013 $plugin->copy_data_phase2($task, $vmid);
1015 debugmsg
('info', "resuming guest", $logfd);
1016 $cleanup->{resume
} = 0;
1017 $self->run_hook_script('pre-restart', $task, $logfd);
1018 $plugin->resume_vm($task, $vmid);
1019 $self->run_hook_script('post-restart', $task, $logfd);
1020 $log_vm_online_again->();
1023 } elsif ($mode eq 'snapshot') {
1024 $self->run_hook_script ('backup-start', $task, $logfd);
1026 my $snapshot_count = $task->{snapshot_count
} || 0;
1028 $self->run_hook_script ('pre-stop', $task, $logfd);
1030 if ($snapshot_count > 1) {
1031 debugmsg
('info', "suspend vm to make snapshot", $logfd);
1032 $task->{vmstoptime
} = time ();
1033 $plugin->suspend_vm ($task, $vmid);
1034 $cleanup->{resume
} = 1;
1037 $plugin->snapshot ($task, $vmid);
1039 $self->run_hook_script ('pre-restart', $task, $logfd);
1041 if ($snapshot_count > 1) {
1042 debugmsg
('info', "resume vm", $logfd);
1043 $cleanup->{resume
} = 0;
1044 $plugin->resume_vm ($task, $vmid);
1045 $log_vm_online_again->();
1048 $self->run_hook_script ('post-restart', $task, $logfd);
1051 die "internal error - unknown mode '$mode'\n";
1054 # assemble archive image
1055 $plugin->assemble ($task, $vmid);
1059 if ($opts->{stdout
}) {
1060 debugmsg
('info', "sending archive to stdout", $logfd);
1061 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
1062 $self->run_hook_script ('backup-end', $task, $logfd);
1066 my $archive_txt = $self->{opts
}->{pbs
} ?
'Proxmox Backup Server' : 'vzdump';
1067 debugmsg
('info', "creating $archive_txt archive '$task->{target}'", $logfd);
1068 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
1070 if ($self->{opts
}->{pbs
}) {
1071 # size is added to task struct in guest vzdump plugins
1073 rename ($task->{tmptar
}, $task->{target
}) ||
1074 die "unable to rename '$task->{tmptar}' to '$task->{target}'\n";
1077 $task->{size
} = (-s
$task->{target
}) || 0;
1078 my $cs = format_size
($task->{size
});
1079 debugmsg
('info', "archive file size: $cs", $logfd);
1082 # Mark as protected before pruning.
1083 if (my $storeid = $opts->{storage
}) {
1084 my $volname = $opts->{pbs
} ?
$task->{target
} : basename
($task->{target
});
1085 my $volid = "${storeid}:backup/${volname}";
1087 if ($opts->{'notes-template'} && $opts->{'notes-template'} ne '') {
1088 debugmsg
('info', "adding notes to backup", $logfd);
1089 my $notes = eval { $generate_notes->($opts->{'notes-template'}, $task); };
1091 debugmsg
('warn', "unable to add notes - $err", $logfd);
1093 eval { PVE
::Storage
::update_volume_attribute
($cfg, $volid, 'notes', $notes) };
1094 debugmsg
('warn', "unable to add notes - $@", $logfd) if $@;
1098 if ($opts->{protected
}) {
1099 debugmsg
('info', "marking backup as protected", $logfd);
1100 eval { PVE
::Storage
::update_volume_attribute
($cfg, $volid, 'protected', 1) };
1101 die "unable to set protected flag - $@\n" if $@;
1105 if ($opts->{remove
}) {
1106 my $keepstr = join(', ', map { "$_=$prune_options->{$_}" } sort keys %$prune_options);
1107 debugmsg
('info', "prune older backups with retention: $keepstr", $logfd);
1109 if (!defined($opts->{storage
})) {
1110 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
1112 PVE
::Storage
::prune_mark_backup_group
($bklist, $prune_options);
1114 foreach my $prune_entry (@{$bklist}) {
1115 next if $prune_entry->{mark
} ne 'remove';
1117 my $archive_path = $prune_entry->{path
};
1118 debugmsg
('info', "delete old backup '$archive_path'", $logfd);
1119 PVE
::Storage
::archive_remove
($archive_path);
1122 my $pruned_list = PVE
::Storage
::prune_backups
(
1129 sub { debugmsg
($_[0], $_[1], $logfd) },
1131 $pruned = scalar(grep { $_->{mark
} eq 'remove' } $pruned_list->@*);
1133 my $log_pruned_extra = $pruned > 0 ?
" not covered by keep-retention policy" : "";
1134 debugmsg
('info', "pruned $pruned backup(s)${log_pruned_extra}", $logfd);
1137 $self->run_hook_script ('backup-end', $task, $logfd);
1144 if ($cleanup->{unlock
}) {
1145 eval { $plugin->unlock_vm ($vmid); };
1149 if ($cleanup->{prepared
}) {
1150 # only call cleanup when necessary (when prepare was executed)
1151 eval { $plugin->cleanup ($task, $vmid) };
1155 eval { $plugin->set_logfd (undef); };
1158 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1160 $self->run_hook_script ('pre-restart', $task, $logfd);
1161 if ($cleanup->{resume
}) {
1162 debugmsg
('info', "resume vm", $logfd);
1163 $plugin->resume_vm ($task, $vmid);
1165 my $running = $plugin->vm_status($vmid);
1167 debugmsg
('info', "restarting vm", $logfd);
1168 $plugin->start_vm ($task, $vmid);
1171 $self->run_hook_script ('post-restart', $task, $logfd);
1177 $log_vm_online_again->();
1182 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1185 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1188 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1191 $task->{state} = 'err';
1192 $task->{msg
} = $err;
1193 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1194 debugmsg
('info', "Failed at " . strftime
("%F %H:%M:%S", localtime()));
1196 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1199 $task->{state} = 'ok';
1200 my $tstr = format_time
($delay);
1201 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1202 debugmsg
('info', "Backup finished at " . strftime
("%F %H:%M:%S", localtime()));
1205 close ($logfd) if $logfd;
1207 if ($task->{tmplog
}) {
1208 if ($self->{opts
}->{pbs
}) {
1209 if ($task->{state} eq 'ok') {
1211 PVE
::Storage
::PBSPlugin
::run_raw_client_cmd
(
1215 [ $pbs_snapshot_name, $task->{tmplog
} ],
1216 errmsg
=> "uploading backup task log failed",
1220 debugmsg
('warn', "$@") if $@; # $@ contains already error prefix
1222 } elsif ($task->{logfile
}) {
1223 system {'cp'} 'cp', $task->{tmplog
}, $task->{logfile
};
1227 eval { $self->run_hook_script ('log-end', $task); };
1229 die $err if $err && $err =~ m/^interrupted by signal$/;
1233 my ($self, $rpcenv, $authuser) = @_;
1235 my $opts = $self->{opts
};
1237 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1239 if (scalar(@{$self->{skiplist
}})) {
1240 my $skip_string = join(', ', sort { $a <=> $b } @{$self->{skiplist
}});
1241 debugmsg
('info', "skip external VMs: $skip_string");
1245 my $vzdump_plugins = {};
1246 foreach my $plugin (@{$self->{plugins
}}) {
1247 my $type = $plugin->type();
1248 next if exists $vzdump_plugins->{$type};
1249 $vzdump_plugins->{$type} = $plugin;
1252 my $vmlist = PVE
::Cluster
::get_vmlist
();
1253 my $vmids = [ sort { $a <=> $b } @{$opts->{vmids
}} ];
1254 foreach my $vmid (@{$vmids}) {
1256 if (defined($vmlist->{ids
}->{$vmid})) {
1257 my $guest_type = $vmlist->{ids
}->{$vmid}->{type
};
1258 $plugin = $vzdump_plugins->{$guest_type};
1259 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], $opts->{all
});
1262 mode
=> $opts->{mode
},
1269 # Use in-memory files for the outer hook logs to pass them to sendmail.
1270 my $job_start_log = '';
1271 my $job_end_log = '';
1272 open my $job_start_fd, '>', \
$job_start_log;
1273 open my $job_end_fd, '>', \
$job_end_log;
1275 my $starttime = time();
1279 $self->run_hook_script ('job-start', undef, $job_start_fd);
1281 foreach my $task (@$tasklist) {
1282 $self->exec_backup_task ($task);
1283 $errcount += 1 if $task->{state} ne 'ok';
1286 $self->run_hook_script ('job-end', undef, $job_end_fd);
1290 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
1293 debugmsg
('err', "Backup job failed - $err", undef, 1);
1296 debugmsg
('info', "Backup job finished with errors", undef, 1);
1298 debugmsg
('info', "Backup job finished successfully", undef, 1);
1302 close $job_start_fd;
1305 my $totaltime = time() - $starttime;
1312 $self->{job_init_log
} . $job_start_log,
1316 debugmsg
('err', $@) if $@;
1320 die "job errors\n" if $errcount;
1328 return defined($confdesc->{$key});
1331 # NOTE it might make sense to merge this and verify_vzdump_parameters(), but one
1332 # needs to adapt command_line() in guest-common's PVE/VZDump/Common.pm and detect
1333 # a second parsing attempt, because verify_vzdump_parameters() is called twice
1334 # during the update_job API call.
1335 sub parse_mailto_exclude_path
{
1338 # exclude-path list need to be 0 separated
1339 if (defined($param->{'exclude-path'})) {
1340 my @expaths = split(/\0/, $param->{'exclude-path'} || '');
1341 $param->{'exclude-path'} = [ @expaths ];
1344 if (defined($param->{mailto
})) {
1345 my @mailto = PVE
::Tools
::split_list
(extract_param
($param, 'mailto'));
1346 $param->{mailto
} = [ @mailto ];
1352 sub verify_vzdump_parameters
{
1353 my ($param, $check_missing) = @_;
1355 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1356 if $param->{all
} && $param->{vmid
};
1358 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1359 if $param->{exclude
} && $param->{vmid
};
1361 raise_param_exc
({ pool
=> "option conflicts with option 'vmid'"})
1362 if $param->{pool
} && $param->{vmid
};
1364 raise_param_exc
({ 'prune-backups' => "option conflicts with option 'maxfiles'"})
1365 if defined($param->{'prune-backups'}) && defined($param->{maxfiles
});
1367 $parse_prune_backups_maxfiles->($param, 'CLI parameters');
1368 parse_performance
($param);
1370 if (my $template = $param->{'notes-template'}) {
1371 eval { $verify_notes_template->($template); };
1372 raise_param_exc
({'notes-template' => $@}) if $@;
1375 $param->{all
} = 1 if (defined($param->{exclude
}) && !$param->{pool
});
1377 return if !$check_missing;
1379 raise_param_exc
({ vmid
=> "property is missing"})
1380 if !($param->{all
} || $param->{stop
} || $param->{pool
}) && !$param->{vmid
};
1384 sub stop_running_backups
{
1387 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1390 my $task = PVE
::Tools
::upid_decode
($upid);
1392 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1393 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1394 kill(15, $task->{pid
});
1395 # wait max 15 seconds to shut down (else, do nothing for now)
1397 for ($i = 15; $i > 0; $i--) {
1398 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1401 die "stopping backup process $task->{pid} failed\n" if $i == 0;
1405 sub get_included_guests
{
1409 my $vmids_per_node = {};
1411 my $vmlist = PVE
::Cluster
::get_vmlist
();
1414 $vmids = PVE
::API2Tools
::get_resource_pool_guest_members
($job->{pool
});
1415 } elsif ($job->{vmid
}) {
1416 $vmids = [ split_list
($job->{vmid
}) ];
1417 } elsif ($job->{all
}) {
1419 my $exclude = check_vmids
(split_list
($job->{exclude
}));
1420 my $excludehash = { map { $_ => 1 } @$exclude };
1422 for my $id (keys %{$vmlist->{ids
}}) {
1423 next if $excludehash->{$id};
1427 return $vmids_per_node;
1429 $vmids = check_vmids
(@$vmids);
1431 for my $vmid (@$vmids) {
1432 if (defined($vmlist->{ids
}->{$vmid})) {
1433 my $node = $vmlist->{ids
}->{$vmid}->{node
};
1434 next if (defined $job->{node
} && $job->{node
} ne $node);
1436 push @{$vmids_per_node->{$node}}, $vmid;
1438 push @{$vmids_per_node->{''}}, $vmid;
1442 return $vmids_per_node;