]>
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);
14 use POSIX
qw(strftime);
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';
24 my $pidfile = '/var/run/vzdump.pid';
25 my $logdir = '/var/log/vzdump';
31 type
=> 'string', format
=> 'pve-vmid-list',
32 description
=> "The ID of the guest system you want to backup.",
33 completion
=> \
&PVE
::Cluster
::complete_local_vmid
,
36 node
=> get_standard_option
('pve-node', {
37 description
=> "Only run if executed on this node.",
38 completion
=> \
&PVE
::Cluster
::get_nodelist
,
43 description
=> "Backup all known guest systems on this host.",
49 description
=> "Exclude temporary files and logs.",
55 description
=> "Compress dump file.",
57 enum
=> ['0', '1', 'gzip', 'lzo'],
62 description
=> "Use pigz instead of gzip when N>0.".
63 " N=1 uses half of cores, N>1 uses N as thread count.",
69 description
=> "Be quiet.",
75 description
=> "Backup mode.",
77 default => 'snapshot',
78 enum
=> [ 'snapshot', 'suspend', 'stop' ],
81 type
=> 'string', format
=> 'pve-vmid-list',
82 description
=> "Exclude specified guest systems (assumes --all)",
86 type
=> 'string', format
=> 'string-alist',
87 description
=> "Exclude certain files/directories (shell globs).",
91 type
=> 'string', format
=> 'string-list',
92 description
=> "Comma-separated list of email addresses that should" .
93 " receive email notifications.",
98 description
=> "Specify when to send an email",
100 enum
=> [ 'always', 'failure' ],
105 description
=> "Store temporary files to specified directory.",
110 description
=> "Store resulting files to specified directory.",
115 description
=> "Use specified hook script.",
118 storage
=> get_standard_option
('pve-storage-id', {
119 description
=> "Store resulting file to this storage.",
120 completion
=> \
&complete_backup_storage
,
125 description
=> "Stop running backup jobs on this host.",
131 description
=> "Unused, will be removed in a future release.",
138 description
=> "Limit I/O bandwidth (KBytes per second).",
145 description
=> "Set CFQ ionice priority.",
153 description
=> "Maximal time to wait for the global lock (minutes).",
156 default => 3*60, # 3 hours
160 description
=> "Maximal time to wait until a guest system is stopped (minutes).",
163 default => 10, # 10 minutes
167 description
=> "Maximal number of backup files per guest system.",
174 description
=> "Remove old backup files if there are more than 'maxfiles' backup files.",
180 description
=> 'Backup all known guest systems included in the specified pool.',
185 # Load available plugins
186 my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
187 foreach my $plug (@pve_vzdump_classes) {
188 my $filename = "/usr/share/perl5/$plug.pm";
189 $filename =~ s!::!/!g;
191 eval { require $filename; };
194 push @plugins, $plug;
204 my ($mtype, $msg, $logfd, $syslog) = @_;
206 PVE
::VZDump
::Plugin
::debugmsg
(@_);
210 my ($logfd, $cmdstr, %param) = @_;
214 debugmsg
('info', $line, $logfd);
217 PVE
::Tools
::run_command
($cmdstr, %param, logfunc
=> $logfunc);
223 my $cfg = PVE
::Storage
::config
();
224 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
225 my $type = $scfg->{type
};
227 die "can't use storage type '$type' for backup\n"
228 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'
229 || $type eq 'cifs' || $type eq 'cephfs'));
230 die "can't use storage '$storage' for backups - wrong content type\n"
231 if (!$scfg->{content
}->{backup
});
233 PVE
::Storage
::activate_storage
($cfg, $storage);
236 dumpdir
=> PVE
::Storage
::get_backup_dir
($cfg, $storage),
237 maxfiles
=> $scfg->{maxfiles
},
244 my $kb = $size / 1024;
247 return int ($kb) . "KB";
250 my $mb = $size / (1024*1024);
253 return int ($mb) . "MB";
256 return sprintf ("%.2fGB", $gb);
263 my $hours = int ($seconds/3600);
264 $seconds = $seconds - $hours*3600;
265 my $min = int ($seconds/60);
266 $seconds = $seconds - $min*60;
268 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
274 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
292 foreach my $p (split (/:/, $ENV{PATH
})) {
299 die "unable to find command '$bin'\n";
306 foreach my $vmid (@vmids) {
307 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
308 $vmid = int ($vmid); # remove leading zeros
317 sub read_vzdump_defaults
{
319 my $fn = "/etc/vzdump.conf";
323 my $default = $confdesc->{$_}->{default};
324 defined($default) ?
($_ => $default) : ()
329 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
330 return $defaults if $@;
332 my $conf_schema = { type
=> 'object', properties
=> $confdesc, };
333 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
334 if (my $excludes = $res->{'exclude-path'}) {
335 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
337 if (defined($res->{mailto
})) {
338 my @mailto = PVE
::Tools
::split_list
($res->{mailto
});
339 $res->{mailto
} = [ @mailto ];
342 foreach my $key (keys %$defaults) {
343 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
350 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
352 my $opts = $self->{opts
};
354 my $mailto = $opts->{mailto
};
356 return if !($mailto && scalar(@$mailto));
358 my $cmdline = $self->{cmdline
};
361 foreach my $task (@$tasklist) {
362 $ecount++ if $task->{state} ne 'ok';
363 chomp $task->{msg
} if $task->{msg
};
364 $task->{backuptime
} = 0 if !$task->{backuptime
};
365 $task->{size
} = 0 if !$task->{size
};
366 $task->{tarfile
} = 'unknown' if !$task->{tarfile
};
367 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
369 if ($task->{state} eq 'todo') {
370 $task->{msg
} = 'aborted';
374 my $notify = $opts->{mailnotification
} || 'always';
375 return if (!$ecount && !$err && ($notify eq 'failure'));
377 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
380 $stat .= ": multiple problems";
387 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
391 my $text = $err ?
"$err\n\n" : '';
392 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
393 foreach my $task (@$tasklist) {
394 my $vmid = $task->{vmid
};
395 if ($task->{state} eq 'ok') {
397 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", $vmid,
399 format_time
($task->{backuptime
}),
400 format_size
($task->{size
}),
403 $text .= sprintf ("%-10s %-6s %10s %8.2fMB %s\n", $vmid,
405 format_time
($task->{backuptime
}),
410 $text .= "\nDetailed backup logs:\n\n";
411 $text .= "$cmdline\n\n";
413 $text .= $detail_pre . "\n" if defined($detail_pre);
414 foreach my $task (@$tasklist) {
415 my $vmid = $task->{vmid
};
416 my $log = $task->{tmplog
};
418 $text .= "$vmid: no log available\n\n";
422 while (my $line = <TMP
>) { $text .= encode8bit
("$vmid: $line"); }
426 $text .= $detail_post if defined($detail_post);
429 my $html = "<html><body>\n";
430 $html .= "<p>" . (escape_html
($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
431 $html .= "<table border=1 cellpadding=3>\n";
432 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
436 foreach my $task (@$tasklist) {
437 my $vmid = $task->{vmid
};
438 my $name = $task->{hostname
};
440 if ($task->{state} eq 'ok') {
442 $ssize += $task->{size
};
444 $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
446 format_time
($task->{backuptime
}),
447 format_size
($task->{size
}),
448 escape_html
($task->{tarfile
}));
450 $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
451 $vmid, $name, format_time
($task->{backuptime
}),
452 escape_html
($task->{msg
}));
456 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
457 format_time
($totaltime), format_size
($ssize));
459 $html .= "</table><br><br>\n";
460 $html .= "Detailed backup logs:<br /><br />\n";
462 $html .= escape_html
($cmdline) . "\n\n";
464 $html .= escape_html
($detail_pre) . "\n" if defined($detail_pre);
465 foreach my $task (@$tasklist) {
466 my $vmid = $task->{vmid
};
467 my $log = $task->{tmplog
};
469 $html .= "$vmid: no log available\n\n";
473 while (my $line = <TMP
>) {
474 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
475 $html .= encode8bit
("$vmid: <font color=red>".
476 escape_html
($line) . "</font>");
478 $html .= encode8bit
("$vmid: " . escape_html
($line));
484 $html .= escape_html
($detail_post) if defined($detail_post);
485 $html .= "</pre></body></html>\n";
488 my $subject = "vzdump backup status ($hostname) : $stat";
490 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
491 my $mailfrom = $dcconf->{email_from
} || "root";
493 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
497 my ($class, $cmdline, $opts, $skiplist) = @_;
503 check_bin
('sendmail');
507 check_bin
('umount');
508 check_bin
('cstream');
509 check_bin
('ionice');
511 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
512 check_bin
('lvcreate');
514 check_bin
('lvremove');
517 my $defaults = read_vzdump_defaults
();
519 my $maxfiles = $opts->{maxfiles
}; # save here, because we overwrite with default
521 $opts->{remove
} = 1 if !defined($opts->{remove
});
523 foreach my $k (keys %$defaults) {
524 next if $k eq 'exclude-path'; # dealt with separately
525 if ($k eq 'dumpdir' || $k eq 'storage') {
526 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
527 !defined ($opts->{storage
});
529 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
533 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
534 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
536 $skiplist = [] if !$skiplist;
537 my $self = bless { cmdline
=> $cmdline, opts
=> $opts, skiplist
=> $skiplist };
539 my $findexcl = $self->{findexcl
} = [];
540 if ($defaults->{'exclude-path'}) {
541 push @$findexcl, @{$defaults->{'exclude-path'}};
544 if ($opts->{'exclude-path'}) {
545 push @$findexcl, @{$opts->{'exclude-path'}};
548 if ($opts->{stdexcludes
}) {
549 push @$findexcl, '/tmp/?*',
554 foreach my $p (@plugins) {
556 my $pd = $p->new ($self);
558 push @{$self->{plugins
}}, $pd;
561 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
562 $opts->{storage
} = 'local';
567 if ($opts->{storage
}) {
568 my $info = eval { storage_info
($opts->{storage
}) };
569 $errors .= "could not get storage information for '$opts->{storage}': $@"
571 $opts->{dumpdir
} = $info->{dumpdir
};
572 $maxfiles //= $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 acquire lock '$lockfile' (wait = 0)", undef, 1);
642 die "can't acquire 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 acquire lock '$lockfile' - $err", undef, 1);
666 die "can't acquire 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 ();
755 my $log_vm_online_again = sub {
756 return if !defined($task->{vmstoptime
});
757 $task->{vmconttime
} //= time();
758 my $delay = $task->{vmconttime
} - $task->{vmstoptime
};
759 debugmsg
('info', "guest is online again after $delay seconds", $logfd);
763 die "unable to find VM '$vmid'\n" if !$plugin;
765 # for now we deny backups of a running ha managed service in *stop* mode
766 # as it interferes with the HA stack (started services should not stop).
767 if ($opts->{mode
} eq 'stop' &&
768 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'started'))
770 die "Cannot execute a backup with stop mode on a HA managed and".
771 " enabled Service. Use snapshot mode or disable the Service.\n";
774 my $vmtype = $plugin->type();
776 my $tmplog = "$logdir/$vmtype-$vmid.log";
778 my $bkname = "vzdump-$vmtype-$vmid";
779 my $basename = $bkname . strftime
("-%Y_%m_%d-%H_%M_%S", localtime());
781 my $maxfiles = $opts->{maxfiles
};
783 if ($maxfiles && !$opts->{remove
}) {
784 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
785 die "There is a max backup limit of ($maxfiles) enforced by the".
786 " target storage or the vzdump parameters.".
787 " Either increase the limit or delete old backup(s).\n"
788 if scalar(@$bklist) >= $maxfiles;
791 my $logfile = $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
793 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
794 my ($comp, $comp_ext) = compressor_info
($opts);
795 if ($comp && $comp_ext) {
796 $ext .= ".${comp_ext}";
799 if ($opts->{stdout
}) {
800 $task->{tarfile
} = '-';
802 my $tarfile = $task->{tarfile
} = "$opts->{dumpdir}/$basename$ext";
803 $task->{tmptar
} = $task->{tarfile
};
804 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
805 unlink $task->{tmptar
};
808 $task->{vmtype
} = $vmtype;
810 if ($opts->{tmpdir
}) {
811 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp$$";
813 # dumpdir is posix? then use it as temporary dir
814 my $info = get_mount_info
($opts->{dumpdir
});
815 if ($vmtype eq 'qemu' ||
816 grep ($_ eq $info->{fstype
}, @posix_filesystems)) {
817 $task->{tmpdir
} = "$opts->{dumpdir}/$basename.tmp";
819 $task->{tmpdir
} = "/var/tmp/vzdumptmp$$";
820 debugmsg
('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
821 "using $task->{tmpdir} for temporary files", $logfd);
825 rmtree
$task->{tmpdir
};
826 mkdir $task->{tmpdir
};
827 -d
$task->{tmpdir
} ||
828 die "unable to create temporary directory '$task->{tmpdir}'";
830 $logfd = IO
::File-
>new (">$tmplog") ||
831 die "unable to create log file '$tmplog'";
833 $task->{dumpdir
} = $opts->{dumpdir
};
834 $task->{storeid
} = $opts->{storage
};
835 $task->{tmplog
} = $tmplog;
839 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
840 debugmsg
('info', "Backup started at " . strftime
("%F %H:%M:%S", localtime()));
842 $plugin->set_logfd ($logfd);
844 # test is VM is running
845 my ($running, $status_text) = $plugin->vm_status ($vmid);
847 debugmsg
('info', "status = ${status_text}", $logfd);
849 # lock VM (prevent config changes)
850 $plugin->lock_vm ($vmid);
852 $cleanup->{unlock
} = 1;
856 my $mode = $running ?
$task->{mode
} : 'stop';
858 if ($mode eq 'snapshot') {
859 my %saved_task = %$task;
860 eval { $plugin->prepare ($task, $vmid, $mode); };
862 die $err if $err !~ m/^mode failure/;
863 debugmsg
('info', $err, $logfd);
864 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
865 $mode = 'suspend'; # so prepare is called again below
866 %$task = %saved_task;
870 $cleanup->{prepared
} = 1;
872 $task->{mode
} = $mode;
874 debugmsg
('info', "backup mode: $mode", $logfd);
876 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
879 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
881 if ($mode eq 'stop') {
883 $plugin->prepare ($task, $vmid, $mode);
885 $self->run_hook_script ('backup-start', $task, $logfd);
888 debugmsg
('info', "stopping vm", $logfd);
889 $task->{vmstoptime
} = time();
890 $self->run_hook_script ('pre-stop', $task, $logfd);
891 $plugin->stop_vm ($task, $vmid);
892 $cleanup->{restart
} = 1;
896 } elsif ($mode eq 'suspend') {
898 $plugin->prepare ($task, $vmid, $mode);
900 $self->run_hook_script ('backup-start', $task, $logfd);
902 if ($vmtype eq 'lxc') {
904 $plugin->copy_data_phase1($task, $vmid);
907 debugmsg
('info', "suspend vm", $logfd);
908 $task->{vmstoptime
} = time ();
909 $self->run_hook_script ('pre-stop', $task, $logfd);
910 $plugin->suspend_vm ($task, $vmid);
911 $cleanup->{resume
} = 1;
913 if ($vmtype eq 'lxc') {
915 $plugin->copy_data_phase2($task, $vmid);
917 debugmsg
('info', "resume vm", $logfd);
918 $cleanup->{resume
} = 0;
919 $self->run_hook_script('pre-restart', $task, $logfd);
920 $plugin->resume_vm($task, $vmid);
921 $self->run_hook_script('post-restart', $task, $logfd);
922 $log_vm_online_again->();
925 } elsif ($mode eq 'snapshot') {
927 $self->run_hook_script ('backup-start', $task, $logfd);
929 my $snapshot_count = $task->{snapshot_count
} || 0;
931 $self->run_hook_script ('pre-stop', $task, $logfd);
933 if ($snapshot_count > 1) {
934 debugmsg
('info', "suspend vm to make snapshot", $logfd);
935 $task->{vmstoptime
} = time ();
936 $plugin->suspend_vm ($task, $vmid);
937 $cleanup->{resume
} = 1;
940 $plugin->snapshot ($task, $vmid);
942 $self->run_hook_script ('pre-restart', $task, $logfd);
944 if ($snapshot_count > 1) {
945 debugmsg
('info', "resume vm", $logfd);
946 $cleanup->{resume
} = 0;
947 $plugin->resume_vm ($task, $vmid);
948 $log_vm_online_again->();
951 $self->run_hook_script ('post-restart', $task, $logfd);
954 die "internal error - unknown mode '$mode'\n";
957 # assemble archive image
958 $plugin->assemble ($task, $vmid);
962 if ($opts->{stdout
}) {
963 debugmsg
('info', "sending archive to stdout", $logfd);
964 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
965 $self->run_hook_script ('backup-end', $task, $logfd);
969 debugmsg
('info', "creating archive '$task->{tarfile}'", $logfd);
970 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
972 rename ($task->{tmptar
}, $task->{tarfile
}) ||
973 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
976 $task->{size
} = (-s
$task->{tarfile
}) || 0;
977 my $cs = format_size
($task->{size
});
978 debugmsg
('info', "archive file size: $cs", $logfd);
982 if ($maxfiles && $opts->{remove
}) {
983 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname, $task->{tarfile
});
984 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
986 while (scalar (@$bklist) >= $maxfiles) {
987 my $d = pop @$bklist;
988 debugmsg
('info', "delete old backup '$d->[0]'", $logfd);
991 $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
996 $self->run_hook_script ('backup-end', $task, $logfd);
1003 if ($cleanup->{unlock
}) {
1004 eval { $plugin->unlock_vm ($vmid); };
1008 if ($cleanup->{prepared
}) {
1009 # only call cleanup when necessary (when prepare was executed)
1010 eval { $plugin->cleanup ($task, $vmid) };
1014 eval { $plugin->set_logfd (undef); };
1017 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1019 $self->run_hook_script ('pre-restart', $task, $logfd);
1020 if ($cleanup->{resume
}) {
1021 debugmsg
('info', "resume vm", $logfd);
1022 $plugin->resume_vm ($task, $vmid);
1024 my $running = $plugin->vm_status($vmid);
1026 debugmsg
('info', "restarting vm", $logfd);
1027 $plugin->start_vm ($task, $vmid);
1030 $self->run_hook_script ('post-restart', $task, $logfd);
1036 $log_vm_online_again->();
1041 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1044 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1047 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1050 $task->{state} = 'err';
1051 $task->{msg
} = $err;
1052 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1053 debugmsg
('info', "Failed at " . strftime
("%F %H:%M:%S", localtime()));
1055 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1058 $task->{state} = 'ok';
1059 my $tstr = format_time
($delay);
1060 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1061 debugmsg
('info', "Backup finished at " . strftime
("%F %H:%M:%S", localtime()));
1064 close ($logfd) if $logfd;
1066 if ($task->{tmplog
} && $task->{logfile
}) {
1067 system {'cp'} 'cp', $task->{tmplog
}, $task->{logfile
};
1070 eval { $self->run_hook_script ('log-end', $task); };
1072 die $err if $err && $err =~ m/^interrupted by signal$/;
1076 my ($self, $rpcenv, $authuser) = @_;
1078 my $opts = $self->{opts
};
1080 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1081 debugmsg
('info', "skip external VMs: " . join(', ', @{$self->{skiplist
}}))
1082 if scalar(@{$self->{skiplist
}});
1087 foreach my $plugin (@{$self->{plugins
}}) {
1088 my $vmlist = $plugin->vmlist();
1089 foreach my $vmid (sort @$vmlist) {
1090 next if grep { $_ eq $vmid } @{$opts->{exclude
}};
1091 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
1092 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin, mode
=> $opts->{mode
} };
1096 foreach my $vmid (sort @{$opts->{vmids
}}) {
1098 foreach my $pg (@{$self->{plugins
}}) {
1099 my $vmlist = $pg->vmlist();
1100 if (grep { $_ eq $vmid } @$vmlist) {
1105 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
1106 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin, mode
=> $opts->{mode
} };
1110 # Use in-memory files for the outer hook logs to pass them to sendmail.
1111 my $job_start_log = '';
1112 my $job_end_log = '';
1113 open my $job_start_fd, '>', \
$job_start_log;
1114 open my $job_end_fd, '>', \
$job_end_log;
1116 my $starttime = time();
1120 $self->run_hook_script ('job-start', undef, $job_start_fd);
1122 foreach my $task (@$tasklist) {
1123 $self->exec_backup_task ($task);
1124 $errcount += 1 if $task->{state} ne 'ok';
1127 $self->run_hook_script ('job-end', undef, $job_end_fd);
1131 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
1134 debugmsg
('err', "Backup job failed - $err", undef, 1);
1137 debugmsg
('info', "Backup job finished with errors", undef, 1);
1139 debugmsg
('info', "Backup job finished successfully", undef, 1);
1143 close $job_start_fd;
1146 my $totaltime = time() - $starttime;
1148 eval { $self->sendmail ($tasklist, $totaltime, undef, $job_start_log, $job_end_log); };
1149 debugmsg
('err', $@) if $@;
1153 die "job errors\n" if $errcount;
1161 return defined($confdesc->{$key});
1164 # add JSON properties for create and set function
1165 sub json_config_properties
{
1168 foreach my $opt (keys %$confdesc) {
1169 $prop->{$opt} = $confdesc->{$opt};
1175 sub verify_vzdump_parameters
{
1176 my ($param, $check_missing) = @_;
1178 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1179 if $param->{all
} && $param->{vmid
};
1181 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1182 if $param->{exclude
} && $param->{vmid
};
1184 raise_param_exc
({ pool
=> "option conflicts with option 'vmid'"})
1185 if $param->{pool
} && $param->{vmid
};
1187 $param->{all
} = 1 if (defined($param->{exclude
}) && !$param->{pool
});
1189 warn "option 'size' is deprecated and will be removed in a future " .
1190 "release, please update your script/configuration!\n"
1191 if defined($param->{size
});
1193 return if !$check_missing;
1195 raise_param_exc
({ vmid
=> "property is missing"})
1196 if !($param->{all
} || $param->{stop
} || $param->{pool
}) && !$param->{vmid
};
1200 sub stop_running_backups
{
1203 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1206 my $task = PVE
::Tools
::upid_decode
($upid);
1208 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1209 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1210 kill(15, $task->{pid
});
1211 # wait max 15 seconds to shut down (else, do nothing for now)
1213 for ($i = 15; $i > 0; $i--) {
1214 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1217 die "stopping backup process $task->{pid} failed\n" if $i == 0;
1226 if ($param->{vmid
}) {
1227 $cmd .= " " . join(' ', PVE
::Tools
::split_list
($param->{vmid
}));
1230 foreach my $p (keys %$param) {
1231 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' ||
1232 $p eq 'dow' || $p eq 'stdout' || $p eq 'enabled';
1233 my $v = $param->{$p};
1234 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
1235 if ($p eq 'exclude-path') {
1236 foreach my $path (split(/\0/, $v || '')) {
1237 $cmd .= " --$p " . PVE
::Tools
::shellquote
($path);
1240 $cmd .= " --$p " . PVE
::Tools
::shellquote
($v) if defined($v) && $v ne '';
1247 # bash completion helpers
1248 sub complete_backup_storage
{
1250 my $cfg = PVE
::Storage
::config
();
1251 my $ids = $cfg->{ids
};
1253 my $nodename = PVE
::INotify
::nodename
();
1256 foreach my $sid (keys %$ids) {
1257 my $scfg = $ids->{$sid};
1258 next if !PVE
::Storage
::storage_check_enabled
($cfg, $sid, $nodename, 1);
1259 next if !$scfg->{content
}->{backup
};