]>
git.proxmox.com Git - pve-manager.git/blob - PVE/VZDump.pm
6 use PVE
::Exception
qw(raise_param_exc);
11 use PVE
::RPCEnvironment
;
13 use PVE
::Cluster
qw(cfs_read_file);
16 use PVE
::JSONSchema
qw(get_standard_option);
17 use PVE
::HA
::Env
::PVE2
;
19 use PVE
::VZDump
::Plugin
;
21 my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
23 my $lockfile = '/var/run/vzdump.lock';
25 my $pidfile = '/var/run/vzdump.pid';
27 my $logdir = '/var/log/vzdump';
33 type
=> 'string', format
=> 'pve-vmid-list',
34 description
=> "The ID of the guest system you want to backup.",
35 completion
=> \
&PVE
::Cluster
::complete_local_vmid
,
38 node
=> get_standard_option
('pve-node', {
39 description
=> "Only run if executed on this node.",
40 completion
=> \
&PVE
::Cluster
::get_nodelist
,
45 description
=> "Backup all known guest systems on this host.",
51 description
=> "Exclude temporary files and logs.",
57 description
=> "Compress dump file.",
59 enum
=> ['0', '1', 'gzip', 'lzo'],
64 description
=> "Use pigz instead of gzip when N>0.".
65 " N=1 uses half of cores, N>1 uses N as thread count.",
71 description
=> "Be quiet.",
77 description
=> "Backup mode.",
79 default => 'snapshot',
80 enum
=> [ 'snapshot', 'suspend', 'stop' ],
83 type
=> 'string', format
=> 'pve-vmid-list',
84 description
=> "Exclude specified guest systems (assumes --all)",
88 type
=> 'string', format
=> 'string-alist',
89 description
=> "Exclude certain files/directories (shell globs).",
93 type
=> 'string', format
=> 'string-list',
94 description
=> "Comma-separated list of email addresses that should" .
95 " receive email notifications.",
100 description
=> "Specify when to send an email",
102 enum
=> [ 'always', 'failure' ],
107 description
=> "Store temporary files to specified directory.",
112 description
=> "Store resulting files to specified directory.",
117 description
=> "Use specified hook script.",
120 storage
=> get_standard_option
('pve-storage-id', {
121 description
=> "Store resulting file to this storage.",
122 completion
=> \
&complete_backup_storage
,
127 description
=> "Stop runnig backup jobs on this host.",
133 description
=> "Unused, will be removed in a future release.",
140 description
=> "Limit I/O bandwidth (KBytes per second).",
147 description
=> "Set CFQ ionice priority.",
155 description
=> "Maximal time to wait for the global lock (minutes).",
158 default => 3*60, # 3 hours
162 description
=> "Maximal time to wait until a guest system is stopped (minutes).",
165 default => 10, # 10 minutes
169 description
=> "Maximal number of backup files per guest system.",
176 description
=> "Remove old backup files if there are more than 'maxfiles' backup files.",
182 # Load available plugins
183 my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
184 foreach my $plug (@pve_vzdump_classes) {
185 my $filename = "/usr/share/perl5/$plug.pm";
186 $filename =~ s!::!/!g;
188 eval { require $filename; };
191 push @plugins, $plug;
201 my ($mtype, $msg, $logfd, $syslog) = @_;
203 PVE
::VZDump
::Plugin
::debugmsg
(@_);
207 my ($logfd, $cmdstr, %param) = @_;
211 debugmsg
('info', $line, $logfd);
214 PVE
::Tools
::run_command
($cmdstr, %param, logfunc
=> $logfunc);
220 my $cfg = PVE
::Storage
::config
();
221 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
222 my $type = $scfg->{type
};
224 die "can't use storage type '$type' for backup\n"
225 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'
226 || $type eq 'cifs' || $type eq 'cephfs'));
227 die "can't use storage '$storage' for backups - wrong content type\n"
228 if (!$scfg->{content
}->{backup
});
230 PVE
::Storage
::activate_storage
($cfg, $storage);
233 dumpdir
=> PVE
::Storage
::get_backup_dir
($cfg, $storage),
234 maxfiles
=> $scfg->{maxfiles
},
241 my $kb = $size / 1024;
244 return int ($kb) . "KB";
247 my $mb = $size / (1024*1024);
250 return int ($mb) . "MB";
253 return sprintf ("%.2fGB", $gb);
260 my $hours = int ($seconds/3600);
261 $seconds = $seconds - $hours*3600;
262 my $min = int ($seconds/60);
263 $seconds = $seconds - $min*60;
265 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
271 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
289 foreach my $p (split (/:/, $ENV{PATH
})) {
296 die "unable to find command '$bin'\n";
303 foreach my $vmid (@vmids) {
304 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
305 $vmid = int ($vmid); # remove leading zeros
314 sub read_vzdump_defaults
{
316 my $fn = "/etc/vzdump.conf";
320 my $default = $confdesc->{$_}->{default};
321 defined($default) ?
($_ => $default) : ()
326 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
327 return $defaults if $@;
329 my $conf_schema = { type
=> 'object', properties
=> $confdesc, };
330 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
331 if (my $excludes = $res->{'exclude-path'}) {
332 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
334 if (defined($res->{mailto
})) {
335 my @mailto = PVE
::Tools
::split_list
($res->{mailto
});
336 $res->{mailto
} = [ @mailto ];
339 foreach my $key (keys %$defaults) {
340 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
347 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
349 my $opts = $self->{opts
};
351 my $mailto = $opts->{mailto
};
353 return if !($mailto && scalar(@$mailto));
355 my $cmdline = $self->{cmdline
};
358 foreach my $task (@$tasklist) {
359 $ecount++ if $task->{state} ne 'ok';
360 chomp $task->{msg
} if $task->{msg
};
361 $task->{backuptime
} = 0 if !$task->{backuptime
};
362 $task->{size
} = 0 if !$task->{size
};
363 $task->{tarfile
} = 'unknown' if !$task->{tarfile
};
364 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
366 if ($task->{state} eq 'todo') {
367 $task->{msg
} = 'aborted';
371 my $notify = $opts->{mailnotification
} || 'always';
372 return if (!$ecount && !$err && ($notify eq 'failure'));
374 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
377 $stat .= ": multiple problems";
384 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
388 my $text = $err ?
"$err\n\n" : '';
389 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
390 foreach my $task (@$tasklist) {
391 my $vmid = $task->{vmid
};
392 if ($task->{state} eq 'ok') {
394 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", $vmid,
396 format_time
($task->{backuptime
}),
397 format_size
($task->{size
}),
400 $text .= sprintf ("%-10s %-6s %10s %8.2fMB %s\n", $vmid,
402 format_time
($task->{backuptime
}),
407 $text .= "\nDetailed backup logs:\n\n";
408 $text .= "$cmdline\n\n";
410 $text .= $detail_pre . "\n" if defined($detail_pre);
411 foreach my $task (@$tasklist) {
412 my $vmid = $task->{vmid
};
413 my $log = $task->{tmplog
};
415 $text .= "$vmid: no log available\n\n";
419 while (my $line = <TMP
>) { $text .= encode8bit
("$vmid: $line"); }
423 $text .= $detail_post if defined($detail_post);
426 my $html = "<html><body>\n";
427 $html .= "<p>" . (escape_html
($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
428 $html .= "<table border=1 cellpadding=3>\n";
429 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
433 foreach my $task (@$tasklist) {
434 my $vmid = $task->{vmid
};
435 my $name = $task->{hostname
};
437 if ($task->{state} eq 'ok') {
439 $ssize += $task->{size
};
441 $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
443 format_time
($task->{backuptime
}),
444 format_size
($task->{size
}),
445 escape_html
($task->{tarfile
}));
447 $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
448 $vmid, $name, format_time
($task->{backuptime
}),
449 escape_html
($task->{msg
}));
453 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
454 format_time
($totaltime), format_size
($ssize));
456 $html .= "</table><br><br>\n";
457 $html .= "Detailed backup logs:<br /><br />\n";
459 $html .= escape_html
($cmdline) . "\n\n";
461 $html .= escape_html
($detail_pre) . "\n" if defined($detail_pre);
462 foreach my $task (@$tasklist) {
463 my $vmid = $task->{vmid
};
464 my $log = $task->{tmplog
};
466 $html .= "$vmid: no log available\n\n";
470 while (my $line = <TMP
>) {
471 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
472 $html .= encode8bit
("$vmid: <font color=red>".
473 escape_html
($line) . "</font>");
475 $html .= encode8bit
("$vmid: " . escape_html
($line));
481 $html .= escape_html
($detail_post) if defined($detail_post);
482 $html .= "</pre></body></html>\n";
485 my $subject = "vzdump backup status ($hostname) : $stat";
487 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
488 my $mailfrom = $dcconf->{email_from
} || "root";
490 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
494 my ($class, $cmdline, $opts, $skiplist) = @_;
500 check_bin
('sendmail');
504 check_bin
('umount');
505 check_bin
('cstream');
506 check_bin
('ionice');
508 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
509 check_bin
('lvcreate');
511 check_bin
('lvremove');
514 my $defaults = read_vzdump_defaults
();
516 my $maxfiles = $opts->{maxfiles
}; # save here, because we overwrite with default
518 $opts->{remove
} = 1 if !defined($opts->{remove
});
520 foreach my $k (keys %$defaults) {
521 next if $k eq 'exclude-path'; # dealt with separately
522 if ($k eq 'dumpdir' || $k eq 'storage') {
523 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
524 !defined ($opts->{storage
});
526 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
530 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
531 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
533 $skiplist = [] if !$skiplist;
534 my $self = bless { cmdline
=> $cmdline, opts
=> $opts, skiplist
=> $skiplist };
536 my $findexcl = $self->{findexcl
} = [];
537 if ($defaults->{'exclude-path'}) {
538 push @$findexcl, @{$defaults->{'exclude-path'}};
541 if ($opts->{'exclude-path'}) {
542 push @$findexcl, @{$opts->{'exclude-path'}};
545 if ($opts->{stdexcludes
}) {
546 push @$findexcl, '/tmp/?*',
551 foreach my $p (@plugins) {
553 my $pd = $p->new ($self);
555 push @{$self->{plugins
}}, $pd;
558 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
559 $opts->{storage
} = 'local';
564 if ($opts->{storage
}) {
567 $info = storage_info
($opts->{storage
});
569 $errors .= "could not get storage information for '$opts->{storage}': $@"
571 $opts->{dumpdir
} = $info->{dumpdir
};
572 $maxfiles = $info->{maxfiles
} if !defined($maxfiles) && defined($info->{maxfiles
});
573 } elsif ($opts->{dumpdir
}) {
574 $errors .= "dumpdir '$opts->{dumpdir}' does not exist"
575 if ! -d
$opts->{dumpdir
};
577 die "internal error";
580 if ($opts->{tmpdir
} && ! -d
$opts->{tmpdir
}) {
581 $errors .= "\n" if $errors;
582 $errors .= "tmpdir '$opts->{tmpdir}' does not exist";
586 eval { $self->sendmail([], 0, $errors); };
587 debugmsg
('err', $@) if $@;
591 $opts->{maxfiles
} = $maxfiles if defined($maxfiles);
600 # Note: df 'available' can be negative, and percentage set to '-'
602 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
608 if (my ($fsid, $fstype, undef, $mp) = $line =~
609 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
618 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
625 my ($self, $upid) = @_;
629 my $maxwait = $self->{opts
}->{lockwait
} || $self->{lockwait
};
631 die "missimg UPID" if !$upid; # should not happen
633 if (!open (SERVER_FLCK
, ">>$lockfile")) {
634 debugmsg
('err', "can't open lock on file '$lockfile' - $!", undef, 1);
635 die "can't open lock on file '$lockfile' - $!";
638 if (!flock (SERVER_FLCK
, LOCK_EX
|LOCK_NB
)) {
641 debugmsg
('err', "can't aquire lock '$lockfile' (wait = 0)", undef, 1);
642 die "can't aquire lock '$lockfile' (wait = 0)";
645 debugmsg
('info', "trying to get global lock - waiting...", undef, 1);
648 alarm ($maxwait * 60);
650 local $SIG{ALRM
} = sub { alarm (0); die "got timeout\n"; };
652 if (!flock (SERVER_FLCK
, LOCK_EX
)) {
665 debugmsg
('err', "can't aquire lock '$lockfile' - $err", undef, 1);
666 die "can't aquire lock '$lockfile' - $err";
669 debugmsg
('info', "got global lock", undef, 1);
672 PVE
::Tools
::file_set_contents
($pidfile, $upid);
675 sub run_hook_script
{
676 my ($self, $phase, $task, $logfd) = @_;
678 my $opts = $self->{opts
};
680 my $script = $opts->{script
};
684 my $cmd = "$script $phase";
686 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
690 # set immutable opts directly (so they are available in all phases)
691 $ENV{STOREID
} = $opts->{storage
} if $opts->{storage
};
692 $ENV{DUMPDIR
} = $opts->{dumpdir
} if $opts->{dumpdir
};
694 foreach my $ek (qw(vmtype hostname tarfile logfile)) {
695 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
698 run_command
($logfd, $cmd);
701 sub compressor_info
{
703 my $opt_compress = $opts->{compress
};
705 if (!$opt_compress || $opt_compress eq '0') {
707 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
708 return ('lzop', 'lzo');
709 } elsif ($opt_compress eq 'gzip') {
710 if ($opts->{pigz
} > 0) {
711 my $pigz_threads = $opts->{pigz
};
712 if ($pigz_threads == 1) {
713 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
714 $pigz_threads = int(($cpuinfo->{cpus
} + 1)/2);
716 return ("pigz -p ${pigz_threads}", 'gz');
718 return ('gzip', 'gz');
721 die "internal error - unknown compression option '$opt_compress'";
725 sub get_backup_file_list
{
726 my ($dir, $bkname, $exclude_fn) = @_;
729 foreach my $fn (<$dir/${bkname
}-*>) {
730 next if $exclude_fn && $fn eq $exclude_fn;
731 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?)))$!) {
732 $fn = "$dir/$1"; # untaint
733 my $t = timelocal
($7, $6, $5, $4, $3 - 1, $2);
734 push @$bklist, [$fn, $t];
741 sub exec_backup_task
{
742 my ($self, $task) = @_;
744 my $opts = $self->{opts
};
746 my $vmid = $task->{vmid
};
747 my $plugin = $task->{plugin
};
749 my $vmstarttime = time ();
758 die "unable to find VM '$vmid'\n" if !$plugin;
760 # for now we deny backups of a running ha managed service in *stop* mode
761 # as it interferes with the HA stack (started services should not stop).
762 if ($opts->{mode
} eq 'stop' &&
763 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'started'))
765 die "Cannot execute a backup with stop mode on a HA managed and".
766 " enabled Service. Use snapshot mode or disable the Service.\n";
769 my $vmtype = $plugin->type();
771 my $tmplog = "$logdir/$vmtype-$vmid.log";
773 my $lt = localtime();
775 my $bkname = "vzdump-$vmtype-$vmid";
776 my $basename = sprintf "${bkname}-%04d_%02d_%02d-%02d_%02d_%02d",
777 $lt->year + 1900, $lt->mon + 1, $lt->mday,
778 $lt->hour, $lt->min, $lt->sec;
780 my $maxfiles = $opts->{maxfiles
};
782 if ($maxfiles && !$opts->{remove
}) {
783 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
784 die "only $maxfiles backup(s) allowed - please consider to remove old backup files.\n"
785 if scalar(@$bklist) >= $maxfiles;
788 my $logfile = $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
790 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
791 my ($comp, $comp_ext) = compressor_info
($opts);
792 if ($comp && $comp_ext) {
793 $ext .= ".${comp_ext}";
796 if ($opts->{stdout
}) {
797 $task->{tarfile
} = '-';
799 my $tarfile = $task->{tarfile
} = "$opts->{dumpdir}/$basename$ext";
800 $task->{tmptar
} = $task->{tarfile
};
801 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
802 unlink $task->{tmptar
};
805 $task->{vmtype
} = $vmtype;
807 if ($opts->{tmpdir
}) {
808 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp$$";
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$$";
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->{tmplog
} = $tmplog;
836 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
838 $plugin->set_logfd ($logfd);
840 # test is VM is running
841 my ($running, $status_text) = $plugin->vm_status ($vmid);
843 debugmsg
('info', "status = ${status_text}", $logfd);
845 # lock VM (prevent config changes)
846 $plugin->lock_vm ($vmid);
848 $cleanup->{unlock
} = 1;
852 my $mode = $running ?
$task->{mode
} : 'stop';
854 if ($mode eq 'snapshot') {
855 my %saved_task = %$task;
856 eval { $plugin->prepare ($task, $vmid, $mode); };
858 die $err if $err !~ m/^mode failure/;
859 debugmsg
('info', $err, $logfd);
860 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
861 $mode = 'suspend'; # so prepare is called again below
862 %$task = %saved_task;
866 $cleanup->{prepared
} = 1;
868 $task->{mode
} = $mode;
870 debugmsg
('info', "backup mode: $mode", $logfd);
872 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
875 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
877 if ($mode eq 'stop') {
879 $plugin->prepare ($task, $vmid, $mode);
881 $self->run_hook_script ('backup-start', $task, $logfd);
884 debugmsg
('info', "stopping vm", $logfd);
885 $vmstoptime = time ();
886 $self->run_hook_script ('pre-stop', $task, $logfd);
887 $plugin->stop_vm ($task, $vmid);
888 $cleanup->{restart
} = 1;
892 } elsif ($mode eq 'suspend') {
894 $plugin->prepare ($task, $vmid, $mode);
896 $self->run_hook_script ('backup-start', $task, $logfd);
898 if ($vmtype eq 'lxc') {
900 $plugin->copy_data_phase1($task, $vmid);
903 debugmsg
('info', "suspend vm", $logfd);
904 $vmstoptime = time ();
905 $self->run_hook_script ('pre-stop', $task, $logfd);
906 $plugin->suspend_vm ($task, $vmid);
907 $cleanup->{resume
} = 1;
909 if ($vmtype eq 'lxc') {
911 $plugin->copy_data_phase2($task, $vmid);
913 debugmsg
('info', "resume vm", $logfd);
914 $cleanup->{resume
} = 0;
915 $self->run_hook_script('pre-restart', $task, $logfd);
916 $plugin->resume_vm($task, $vmid);
917 $self->run_hook_script('post-restart', $task, $logfd);
918 my $delay = time () - $vmstoptime;
919 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
922 } elsif ($mode eq 'snapshot') {
924 $self->run_hook_script ('backup-start', $task, $logfd);
926 my $snapshot_count = $task->{snapshot_count
} || 0;
928 $self->run_hook_script ('pre-stop', $task, $logfd);
930 if ($snapshot_count > 1) {
931 debugmsg
('info', "suspend vm to make snapshot", $logfd);
932 $vmstoptime = time ();
933 $plugin->suspend_vm ($task, $vmid);
934 $cleanup->{resume
} = 1;
937 $plugin->snapshot ($task, $vmid);
939 $self->run_hook_script ('pre-restart', $task, $logfd);
941 if ($snapshot_count > 1) {
942 debugmsg
('info', "resume vm", $logfd);
943 $cleanup->{resume
} = 0;
944 $plugin->resume_vm ($task, $vmid);
945 my $delay = time () - $vmstoptime;
946 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
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 debugmsg
('info', "creating archive '$task->{tarfile}'", $logfd);
968 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
970 rename ($task->{tmptar
}, $task->{tarfile
}) ||
971 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
974 $task->{size
} = (-s
$task->{tarfile
}) || 0;
975 my $cs = format_size
($task->{size
});
976 debugmsg
('info', "archive file size: $cs", $logfd);
980 if ($maxfiles && $opts->{remove
}) {
981 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname, $task->{tarfile
});
982 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
984 while (scalar (@$bklist) >= $maxfiles) {
985 my $d = pop @$bklist;
986 debugmsg
('info', "delete old backup '$d->[0]'", $logfd);
989 $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
994 $self->run_hook_script ('backup-end', $task, $logfd);
1001 if ($cleanup->{unlock
}) {
1002 eval { $plugin->unlock_vm ($vmid); };
1006 if ($cleanup->{prepared
}) {
1007 # only call cleanup when necessary (when prepare was executed)
1008 eval { $plugin->cleanup ($task, $vmid) };
1012 eval { $plugin->set_logfd (undef); };
1015 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1017 $self->run_hook_script ('pre-restart', $task, $logfd);
1018 if ($cleanup->{resume
}) {
1019 debugmsg
('info', "resume vm", $logfd);
1020 $plugin->resume_vm ($task, $vmid);
1022 my $running = $plugin->vm_status($vmid);
1024 debugmsg
('info', "restarting vm", $logfd);
1025 $plugin->start_vm ($task, $vmid);
1028 $self->run_hook_script ('post-restart', $task, $logfd);
1034 my $delay = time () - $vmstoptime;
1035 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
1040 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1043 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1046 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1049 $task->{state} = 'err';
1050 $task->{msg
} = $err;
1051 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1053 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1056 $task->{state} = 'ok';
1057 my $tstr = format_time
($delay);
1058 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1061 close ($logfd) if $logfd;
1063 if ($task->{tmplog
} && $task->{logfile
}) {
1064 system {'cp'} 'cp', $task->{tmplog
}, $task->{logfile
};
1067 eval { $self->run_hook_script ('log-end', $task); };
1069 die $err if $err && $err =~ m/^interrupted by signal$/;
1073 my ($self, $rpcenv, $authuser) = @_;
1075 my $opts = $self->{opts
};
1077 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1078 debugmsg
('info', "skip external VMs: " . join(', ', @{$self->{skiplist
}}))
1079 if scalar(@{$self->{skiplist
}});
1084 foreach my $plugin (@{$self->{plugins
}}) {
1085 my $vmlist = $plugin->vmlist();
1086 foreach my $vmid (sort @$vmlist) {
1087 next if grep { $_ eq $vmid } @{$opts->{exclude
}};
1088 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
1089 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin, mode
=> $opts->{mode
} };
1093 foreach my $vmid (sort @{$opts->{vmids
}}) {
1095 foreach my $pg (@{$self->{plugins
}}) {
1096 my $vmlist = $pg->vmlist();
1097 if (grep { $_ eq $vmid } @$vmlist) {
1102 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
1103 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin, mode
=> $opts->{mode
} };
1107 # Use in-memory files for the outer hook logs to pass them to sendmail.
1108 my $job_start_log = '';
1109 my $job_end_log = '';
1110 open my $job_start_fd, '>', \
$job_start_log;
1111 open my $job_end_fd, '>', \
$job_end_log;
1113 my $starttime = time();
1117 $self->run_hook_script ('job-start', undef, $job_start_fd);
1119 foreach my $task (@$tasklist) {
1120 $self->exec_backup_task ($task);
1121 $errcount += 1 if $task->{state} ne 'ok';
1124 $self->run_hook_script ('job-end', undef, $job_end_fd);
1128 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
1131 debugmsg
('err', "Backup job failed - $err", undef, 1);
1134 debugmsg
('info', "Backup job finished with errors", undef, 1);
1136 debugmsg
('info', "Backup job finished successfully", undef, 1);
1140 close $job_start_fd;
1143 my $totaltime = time() - $starttime;
1145 eval { $self->sendmail ($tasklist, $totaltime, undef, $job_start_log, $job_end_log); };
1146 debugmsg
('err', $@) if $@;
1150 die "job errors\n" if $errcount;
1158 return defined($confdesc->{$key});
1161 # add JSON properties for create and set function
1162 sub json_config_properties
{
1165 foreach my $opt (keys %$confdesc) {
1166 $prop->{$opt} = $confdesc->{$opt};
1172 sub verify_vzdump_parameters
{
1173 my ($param, $check_missing) = @_;
1175 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1176 if $param->{all
} && $param->{vmid
};
1178 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1179 if $param->{exclude
} && $param->{vmid
};
1181 $param->{all
} = 1 if defined($param->{exclude
});
1183 warn "option 'size' is deprecated and will be removed in a future " .
1184 "release, please update your script/configuration!\n"
1185 if defined($param->{size
});
1187 return if !$check_missing;
1189 raise_param_exc
({ vmid
=> "property is missing"})
1190 if !($param->{all
} || $param->{stop
}) && !$param->{vmid
};
1194 sub stop_running_backups
{
1197 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1200 my $task = PVE
::Tools
::upid_decode
($upid);
1202 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1203 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1204 kill(15, $task->{pid
});
1205 # wait max 15 seconds to shut down (else, do nothing for now)
1207 for ($i = 15; $i > 0; $i--) {
1208 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1211 die "stoping backup process $task->{pid} failed\n" if $i == 0;
1220 if ($param->{vmid
}) {
1221 $cmd .= " " . join(' ', PVE
::Tools
::split_list
($param->{vmid
}));
1224 foreach my $p (keys %$param) {
1225 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' ||
1226 $p eq 'dow' || $p eq 'stdout' || $p eq 'enabled';
1227 my $v = $param->{$p};
1228 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
1229 if ($p eq 'exclude-path') {
1230 foreach my $path (split(/\0/, $v || '')) {
1231 $cmd .= " --$p " . PVE
::Tools
::shellquote
($path);
1234 $cmd .= " --$p " . PVE
::Tools
::shellquote
($v) if defined($v) && $v ne '';
1241 # bash completion helpers
1242 sub complete_backup_storage
{
1244 my $cfg = PVE
::Storage
::config
();
1245 my $ids = $cfg->{ids
};
1247 my $nodename = PVE
::INotify
::nodename
();
1250 foreach my $sid (keys %$ids) {
1251 my $scfg = $ids->{$sid};
1252 next if !PVE
::Storage
::storage_check_enabled
($cfg, $sid, $nodename, 1);
1253 next if !$scfg->{content
}->{backup
};