]>
git.proxmox.com Git - pve-manager.git/blob - PVE/VZDump.pm
6 use PVE
::Exception
qw(raise_param_exc);
11 use POSIX
qw(strftime);
13 use PVE
::RPCEnvironment
;
15 use PVE
::Cluster
qw(cfs_read_file);
18 use PVE
::JSONSchema
qw(get_standard_option);
19 use PVE
::HA
::Env
::PVE2
;
22 my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
24 my $lockfile = '/var/run/vzdump.lock';
26 my $pidfile = '/var/run/vzdump.pid';
28 my $logdir = '/var/log/vzdump';
34 type
=> 'string', format
=> 'pve-vmid-list',
35 description
=> "The ID of the VM you want to backup.",
36 completion
=> \
&PVE
::Cluster
::complete_local_vmid
,
39 node
=> get_standard_option
('pve-node', {
40 description
=> "Only run if executed on this node.",
41 completion
=> \
&PVE
::Cluster
::get_nodelist
,
46 description
=> "Backup all known VMs on this host.",
52 description
=> "Exclude temorary files and logs.",
58 description
=> "Compress dump file.",
60 enum
=> ['0', '1', 'gzip', 'lzo'],
65 description
=> "Uses pigz instead of gzip when N>0.".
66 " N=1 uses half of cores, N>1 uses N as thread count.",
72 description
=> "Be quiet.",
78 description
=> "Backup mode.",
80 default => 'snapshot',
81 enum
=> [ 'snapshot', 'suspend', 'stop' ],
84 type
=> 'string', format
=> 'pve-vmid-list',
85 description
=> "exclude specified VMs (assumes --all)",
89 type
=> 'string', format
=> 'string-alist',
90 description
=> "exclude certain files/directories (shell globs).",
94 type
=> 'string', format
=> 'string-list',
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
=> "LVM snapshot size in MB.",
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 VM is stopped (minutes).",
165 default => 10, # 10 minutes
169 description
=> "Maximal number of backup files per VM.",
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;
207 my ($mtype, $msg, $logfd, $syslog) = @_;
213 my $pre = $debugstattxt->{$mtype} || $debugstattxt->{'err'};
215 my $timestr = strftime
("%b %d %H:%M:%S", CORE
::localtime);
217 syslog
($mtype eq 'info' ?
'info' : 'err', "$pre $msg") if $syslog;
219 foreach my $line (split (/\n/, $msg)) {
220 print STDERR
"$pre $line\n";
221 print $logfd "$timestr $pre $line\n" if $logfd;
226 my ($logfd, $cmdstr, %param) = @_;
230 debugmsg
('info', $line, $logfd);
233 PVE
::Tools
::run_command
($cmdstr, %param, logfunc
=> $logfunc);
239 my $cfg = PVE
::Storage
::config
();
240 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
241 my $type = $scfg->{type
};
243 die "can't use storage type '$type' for backup\n"
244 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'));
245 die "can't use storage '$storage' for backups - wrong content type\n"
246 if (!$scfg->{content
}->{backup
});
248 PVE
::Storage
::activate_storage
($cfg, $storage);
251 dumpdir
=> PVE
::Storage
::get_backup_dir
($cfg, $storage),
252 maxfiles
=> $scfg->{maxfiles
},
259 my $kb = $size / 1024;
262 return int ($kb) . "KB";
265 my $mb = $size / (1024*1024);
268 return int ($mb) . "MB";
271 return sprintf ("%.2fGB", $gb);
278 my $hours = int ($seconds/3600);
279 $seconds = $seconds - $hours*3600;
280 my $min = int ($seconds/60);
281 $seconds = $seconds - $min*60;
283 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
289 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
307 foreach my $p (split (/:/, $ENV{PATH
})) {
314 die "unable to find command '$bin'\n";
321 foreach my $vmid (@vmids) {
322 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
323 $vmid = int ($vmid); # remove leading zeros
332 sub read_vzdump_defaults
{
334 my $fn = "/etc/vzdump.conf";
338 my $default = $confdesc->{$_}->{default};
339 defined($default) ?
($_ => $default) : ()
344 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
345 return $defaults if $@;
347 my $conf_schema = { type
=> 'object', properties
=> $confdesc, };
348 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
349 if (my $excludes = $res->{'exclude-path'}) {
350 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
353 foreach my $key (keys %$defaults) {
354 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
361 my ($self, $tasklist, $totaltime, $err) = @_;
363 my $opts = $self->{opts
};
365 my $mailto = $opts->{mailto
};
367 return if !($mailto && scalar(@$mailto));
369 my $cmdline = $self->{cmdline
};
372 foreach my $task (@$tasklist) {
373 $ecount++ if $task->{state} ne 'ok';
374 chomp $task->{msg
} if $task->{msg
};
375 $task->{backuptime
} = 0 if !$task->{backuptime
};
376 $task->{size
} = 0 if !$task->{size
};
377 $task->{tarfile
} = 'unknown' if !$task->{tarfile
};
378 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
380 if ($task->{state} eq 'todo') {
381 $task->{msg
} = 'aborted';
385 my $notify = $opts->{mailnotification
} || 'always';
386 return if (!$ecount && !$err && ($notify eq 'failure'));
388 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
389 $stat .= ": $err" if $err;
391 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
395 my $text = sprintf ("%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
396 foreach my $task (@$tasklist) {
397 my $vmid = $task->{vmid
};
398 if ($task->{state} eq 'ok') {
400 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", $vmid,
402 format_time
($task->{backuptime
}),
403 format_size
($task->{size
}),
406 $text .= sprintf ("%-10s %-6s %10s %8.2fMB %s\n", $vmid,
408 format_time
($task->{backuptime
}),
413 $text .= "Detailed backup logs:\n\n";
414 $text .= "$cmdline\n\n";
416 foreach my $task (@$tasklist) {
417 my $vmid = $task->{vmid
};
418 my $log = $task->{tmplog
};
420 $text .= "$vmid: no log available\n\n";
424 while (my $line = <TMP
>) { $text .= encode8bit
("$vmid: $line"); }
430 my $html = "<html><body>\n";
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 foreach my $task (@$tasklist) {
465 my $vmid = $task->{vmid
};
466 my $log = $task->{tmplog
};
468 $html .= "$vmid: no log available\n\n";
472 while (my $line = <TMP
>) {
473 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
474 $html .= encode8bit
("$vmid: <font color=red>".
475 escape_html
($line) . "</font>");
477 $html .= encode8bit
("$vmid: " . escape_html
($line));
483 $html .= "</pre></body></html>\n";
486 my $subject = "vzdump backup status ($hostname) : $stat";
488 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
489 my $mailfrom = $dcconf->{email_from
} || "root";
491 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
495 my ($class, $cmdline, $opts, $skiplist) = @_;
501 check_bin
('sendmail');
505 check_bin
('umount');
506 check_bin
('cstream');
507 check_bin
('ionice');
509 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
510 check_bin
('lvcreate');
512 check_bin
('lvremove');
515 my $defaults = read_vzdump_defaults
();
517 my $maxfiles = $opts->{maxfiles
}; # save here, because we overwrite with default
519 $opts->{remove
} = 1 if !defined($opts->{remove
});
521 foreach my $k (keys %$defaults) {
522 next if $k eq 'exclude-path'; # dealt with separately
523 if ($k eq 'dumpdir' || $k eq 'storage') {
524 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
525 !defined ($opts->{storage
});
527 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
531 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
532 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
534 $skiplist = [] if !$skiplist;
535 my $self = bless { cmdline
=> $cmdline, opts
=> $opts, skiplist
=> $skiplist };
537 my $findexcl = $self->{findexcl
} = [];
538 if ($defaults->{'exclude-path'}) {
539 push @$findexcl, @{$defaults->{'exclude-path'}};
542 if ($opts->{'exclude-path'}) {
543 push @$findexcl, @{$opts->{'exclude-path'}};
546 if ($opts->{stdexcludes
}) {
547 push @$findexcl, '/var/log/?*',
553 foreach my $p (@plugins) {
555 my $pd = $p->new ($self);
557 push @{$self->{plugins
}}, $pd;
560 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
561 $opts->{storage
} = 'local';
564 if ($opts->{storage
}) {
565 my $info = storage_info
($opts->{storage
});
566 $opts->{dumpdir
} = $info->{dumpdir
};
567 $maxfiles = $info->{maxfiles
} if !defined($maxfiles) && defined($info->{maxfiles
});
568 } elsif ($opts->{dumpdir
}) {
569 die "dumpdir '$opts->{dumpdir}' does not exist\n"
570 if ! -d
$opts->{dumpdir
};
572 die "internal error";
575 if ($opts->{tmpdir
} && ! -d
$opts->{tmpdir
}) {
576 die "tmpdir '$opts->{tmpdir}' does not exist\n";
579 $opts->{maxfiles
} = $maxfiles if defined($maxfiles);
585 sub get_lvm_mapping
{
589 my $cmd = ['lvs', '--units', 'm', '--separator', ':', '--noheadings',
590 '-o', 'vg_name,lv_name,lv_size' ];
594 if ($line =~ m
|^\s
*(\S
+):(\S
+):(\d
+(\
.\d
+))[Mm
]$|) {
597 $devmapper->{"/dev/$vg/$lv"} = [$vg, $lv];
602 $devmapper->{"/dev/mapper/$qvg-$qlv"} = [$vg, $lv];
606 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
615 # Note: df 'available' can be negative, and percentage set to '-'
617 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
623 if (my ($fsid, $fstype, undef, $mp) = $line =~
624 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
633 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
640 my ($dir, $mapping) = @_;
642 my $info = get_mount_info
($dir);
644 return undef if !$info;
646 my $dev = $info->{device
};
650 ($vg, $lv) = @{$mapping->{$dev}} if defined $mapping->{$dev};
652 return wantarray ?
($dev, $info->{mountpoint
}, $vg, $lv, $info->{fstype
}) : $dev;
656 my ($self, $upid) = @_;
660 my $maxwait = $self->{opts
}->{lockwait
} || $self->{lockwait
};
662 die "missimg UPID" if !$upid; # should not happen
664 if (!open (SERVER_FLCK
, ">>$lockfile")) {
665 debugmsg
('err', "can't open lock on file '$lockfile' - $!", undef, 1);
666 die "can't open lock on file '$lockfile' - $!";
669 if (!flock (SERVER_FLCK
, LOCK_EX
|LOCK_NB
)) {
672 debugmsg
('err', "can't aquire lock '$lockfile' (wait = 0)", undef, 1);
673 die "can't aquire lock '$lockfile' (wait = 0)";
676 debugmsg
('info', "trying to get global lock - waiting...", undef, 1);
679 alarm ($maxwait * 60);
681 local $SIG{ALRM
} = sub { alarm (0); die "got timeout\n"; };
683 if (!flock (SERVER_FLCK
, LOCK_EX
)) {
696 debugmsg
('err', "can't aquire lock '$lockfile' - $err", undef, 1);
697 die "can't aquire lock '$lockfile' - $err";
700 debugmsg
('info', "got global lock", undef, 1);
703 PVE
::Tools
::file_set_contents
($pidfile, $upid);
706 sub run_hook_script
{
707 my ($self, $phase, $task, $logfd) = @_;
709 my $opts = $self->{opts
};
711 my $script = $opts->{script
};
715 my $cmd = "$script $phase";
717 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
721 # set immutable opts directly (so they are available in all phases)
722 $ENV{STOREID
} = $opts->{storage
} if $opts->{storage
};
723 $ENV{DUMPDIR
} = $opts->{dumpdir
} if $opts->{dumpdir
};
725 foreach my $ek (qw(vmtype hostname tarfile logfile)) {
726 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
729 run_command
($logfd, $cmd);
732 sub compressor_info
{
734 my $opt_compress = $opts->{compress
};
736 if (!$opt_compress || $opt_compress eq '0') {
738 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
739 return ('lzop', 'lzo');
740 } elsif ($opt_compress eq 'gzip') {
741 if ($opts->{pigz
} > 0) {
742 # As default use int((#cores + 1)/2), we need #cores+1 for the case that #cores = 1
743 my $cores = POSIX
::sysconf
(84);
744 my $pigz_threads = ($opts->{pigz
} > 1) ?
$opts->{pigz
} : int(($cores + 1)/2);
745 return ("pigz -p ${pigz_threads}", 'gz');
747 return ('gzip', 'gz');
750 die "internal error - unknown compression option '$opt_compress'";
754 sub get_backup_file_list
{
755 my ($dir, $bkname, $exclude_fn) = @_;
758 foreach my $fn (<$dir/${bkname
}-*>) {
759 next if $exclude_fn && $fn eq $exclude_fn;
760 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?)))$!) {
761 $fn = "$dir/$1"; # untaint
762 my $t = timelocal
($7, $6, $5, $4, $3 - 1, $2 - 1900);
763 push @$bklist, [$fn, $t];
770 sub exec_backup_task
{
771 my ($self, $task) = @_;
773 my $opts = $self->{opts
};
775 my $vmid = $task->{vmid
};
776 my $plugin = $task->{plugin
};
778 my $vmstarttime = time ();
787 die "unable to find VM '$vmid'\n" if !$plugin;
789 # for now we deny backups of a running ha managed service in *stop* mode
790 # as it interferes with the HA stack (enabled services should not stop).
791 if ($opts->{mode
} eq 'stop' &&
792 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'enabled'))
794 die "Cannot execute a backup with stop mode on a HA managed and".
795 " enabled Service. Use snapshot mode or disable the Service.\n";
798 my $vmtype = $plugin->type();
800 my $tmplog = "$logdir/$vmtype-$vmid.log";
802 my $lt = localtime();
804 my $bkname = "vzdump-$vmtype-$vmid";
805 my $basename = sprintf "${bkname}-%04d_%02d_%02d-%02d_%02d_%02d",
806 $lt->year + 1900, $lt->mon + 1, $lt->mday,
807 $lt->hour, $lt->min, $lt->sec;
809 my $maxfiles = $opts->{maxfiles
};
811 if ($maxfiles && !$opts->{remove
}) {
812 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
813 die "only $maxfiles backup(s) allowed - please consider to remove old backup files.\n"
814 if scalar(@$bklist) >= $maxfiles;
817 my $logfile = $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
819 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
820 my ($comp, $comp_ext) = compressor_info
($opts);
821 if ($comp && $comp_ext) {
822 $ext .= ".${comp_ext}";
825 if ($opts->{stdout
}) {
826 $task->{tarfile
} = '-';
828 my $tarfile = $task->{tarfile
} = "$opts->{dumpdir}/$basename$ext";
829 $task->{tmptar
} = $task->{tarfile
};
830 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
831 unlink $task->{tmptar
};
834 $task->{vmtype
} = $vmtype;
836 if ($opts->{tmpdir
}) {
837 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp$$";
839 # dumpdir is posix? then use it as temporary dir
840 my $info = get_mount_info
($opts->{dumpdir
});
841 if ($vmtype eq 'qemu' ||
842 grep ($_ eq $info->{fstype
}, @posix_filesystems)) {
843 $task->{tmpdir
} = "$opts->{dumpdir}/$basename.tmp";
845 $task->{tmpdir
} = "/var/tmp/vzdumptmp$$";
846 debugmsg
('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
847 "using $task->{tmpdir} for temporary files", $logfd);
851 rmtree
$task->{tmpdir
};
852 mkdir $task->{tmpdir
};
853 -d
$task->{tmpdir
} ||
854 die "unable to create temporary directory '$task->{tmpdir}'";
856 $logfd = IO
::File-
>new (">$tmplog") ||
857 die "unable to create log file '$tmplog'";
859 $task->{dumpdir
} = $opts->{dumpdir
};
860 $task->{storeid
} = $opts->{storage
};
861 $task->{tmplog
} = $tmplog;
865 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
867 $plugin->set_logfd ($logfd);
869 # test is VM is running
870 my ($running, $status_text) = $plugin->vm_status ($vmid);
872 debugmsg
('info', "status = ${status_text}", $logfd);
874 # lock VM (prevent config changes)
875 $plugin->lock_vm ($vmid);
877 $cleanup->{unlock
} = 1;
881 my $mode = $running ?
$opts->{mode
} : 'stop';
883 if ($mode eq 'snapshot') {
884 my %saved_task = %$task;
885 eval { $plugin->prepare ($task, $vmid, $mode); };
887 die $err if $err !~ m/^mode failure/;
888 debugmsg
('info', $err, $logfd);
889 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
890 $mode = 'suspend'; # so prepare is called again below
891 %$task = %saved_task;
895 $task->{mode
} = $mode;
897 debugmsg
('info', "backup mode: $mode", $logfd);
899 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
902 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
904 if ($mode eq 'stop') {
906 $plugin->prepare ($task, $vmid, $mode);
908 $self->run_hook_script ('backup-start', $task, $logfd);
911 debugmsg
('info', "stopping vm", $logfd);
912 $vmstoptime = time ();
913 $self->run_hook_script ('pre-stop', $task, $logfd);
914 $plugin->stop_vm ($task, $vmid);
915 $cleanup->{restart
} = 1;
919 } elsif ($mode eq 'suspend') {
921 $plugin->prepare ($task, $vmid, $mode);
923 $self->run_hook_script ('backup-start', $task, $logfd);
925 if ($vmtype eq 'lxc') {
927 $plugin->copy_data_phase1($task, $vmid);
930 debugmsg
('info', "suspend vm", $logfd);
931 $vmstoptime = time ();
932 $self->run_hook_script ('pre-stop', $task, $logfd);
933 $plugin->suspend_vm ($task, $vmid);
934 $cleanup->{resume
} = 1;
936 if ($vmtype eq 'lxc') {
938 $plugin->copy_data_phase2($task, $vmid);
940 debugmsg
('info', "resume vm", $logfd);
941 $cleanup->{resume
} = 0;
942 $self->run_hook_script('pre-restart', $task, $logfd);
943 $plugin->resume_vm($task, $vmid);
944 my $delay = time () - $vmstoptime;
945 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
948 } elsif ($mode eq 'snapshot') {
950 $self->run_hook_script ('backup-start', $task, $logfd);
952 my $snapshot_count = $task->{snapshot_count
} || 0;
954 $self->run_hook_script ('pre-stop', $task, $logfd);
956 if ($snapshot_count > 1) {
957 debugmsg
('info', "suspend vm to make snapshot", $logfd);
958 $vmstoptime = time ();
959 $plugin->suspend_vm ($task, $vmid);
960 $cleanup->{resume
} = 1;
963 $plugin->snapshot ($task, $vmid);
965 $self->run_hook_script ('pre-restart', $task, $logfd);
967 if ($snapshot_count > 1) {
968 debugmsg
('info', "resume vm", $logfd);
969 $cleanup->{resume
} = 0;
970 $plugin->resume_vm ($task, $vmid);
971 my $delay = time () - $vmstoptime;
972 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
976 die "internal error - unknown mode '$mode'\n";
979 # assemble archive image
980 $plugin->assemble ($task, $vmid);
984 if ($opts->{stdout
}) {
985 debugmsg
('info', "sending archive to stdout", $logfd);
986 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
987 $self->run_hook_script ('backup-end', $task, $logfd);
991 debugmsg
('info', "creating archive '$task->{tarfile}'", $logfd);
992 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
994 rename ($task->{tmptar
}, $task->{tarfile
}) ||
995 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
998 $task->{size
} = (-s
$task->{tarfile
}) || 0;
999 my $cs = format_size
($task->{size
});
1000 debugmsg
('info', "archive file size: $cs", $logfd);
1002 # purge older backup
1004 if ($maxfiles && $opts->{remove
}) {
1005 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname, $task->{tarfile
});
1006 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
1008 while (scalar (@$bklist) >= $maxfiles) {
1009 my $d = pop @$bklist;
1010 debugmsg
('info', "delete old backup '$d->[0]'", $logfd);
1012 my $logfn = $d->[0];
1013 $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
1018 $self->run_hook_script ('backup-end', $task, $logfd);
1025 if ($cleanup->{unlock
}) {
1026 eval { $plugin->unlock_vm ($vmid); };
1030 if (defined($task->{mode
})) {
1031 # only call cleanup when necessary (when prepare was executed)
1032 eval { $plugin->cleanup ($task, $vmid) };
1036 eval { $plugin->set_logfd (undef); };
1039 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1041 $self->run_hook_script ('pre-restart', $task, $logfd);
1042 if ($cleanup->{resume
}) {
1043 debugmsg
('info', "resume vm", $logfd);
1044 $plugin->resume_vm ($task, $vmid);
1046 my $running = $plugin->vm_status($vmid);
1048 debugmsg
('info', "restarting vm", $logfd);
1049 $plugin->start_vm ($task, $vmid);
1057 my $delay = time () - $vmstoptime;
1058 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
1063 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1066 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1069 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1072 $task->{state} = 'err';
1073 $task->{msg
} = $err;
1074 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1076 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1079 $task->{state} = 'ok';
1080 my $tstr = format_time
($delay);
1081 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1084 close ($logfd) if $logfd;
1086 if ($task->{tmplog
} && $task->{logfile
}) {
1087 system ("cp '$task->{tmplog}' '$task->{logfile}'");
1090 eval { $self->run_hook_script ('log-end', $task); };
1092 die $err if $err && $err =~ m/^interrupted by signal$/;
1096 my ($self, $rpcenv, $authuser) = @_;
1098 my $opts = $self->{opts
};
1100 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1101 debugmsg
('info', "skip external VMs: " . join(', ', @{$self->{skiplist
}}))
1102 if scalar(@{$self->{skiplist
}});
1107 foreach my $plugin (@{$self->{plugins
}}) {
1108 my $vmlist = $plugin->vmlist();
1109 foreach my $vmid (sort @$vmlist) {
1110 next if grep { $_ eq $vmid } @{$opts->{exclude
}};
1111 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
1112 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin };
1116 foreach my $vmid (sort @{$opts->{vmids
}}) {
1118 foreach my $pg (@{$self->{plugins
}}) {
1119 my $vmlist = $pg->vmlist();
1120 if (grep { $_ eq $vmid } @$vmlist) {
1125 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
1126 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin };
1130 my $starttime = time();
1134 $self->run_hook_script ('job-start');
1136 foreach my $task (@$tasklist) {
1137 $self->exec_backup_task ($task);
1138 $errcount += 1 if $task->{state} ne 'ok';
1141 $self->run_hook_script ('job-end');
1145 $self->run_hook_script ('job-abort') if $err;
1148 debugmsg
('err', "Backup job failed - $err", undef, 1);
1151 debugmsg
('info', "Backup job finished with errors", undef, 1);
1153 debugmsg
('info', "Backup job finished successfully", undef, 1);
1157 my $totaltime = time() - $starttime;
1159 eval { $self->sendmail ($tasklist, $totaltime); };
1160 debugmsg
('err', $@) if $@;
1164 die "job errors\n" if $errcount;
1172 return defined($confdesc->{$key});
1175 # add JSON properties for create and set function
1176 sub json_config_properties
{
1179 foreach my $opt (keys %$confdesc) {
1180 $prop->{$opt} = $confdesc->{$opt};
1186 sub verify_vzdump_parameters
{
1187 my ($param, $check_missing) = @_;
1189 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1190 if $param->{all
} && $param->{vmid
};
1192 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1193 if $param->{exclude
} && $param->{vmid
};
1195 $param->{all
} = 1 if defined($param->{exclude
});
1197 return if !$check_missing;
1199 raise_param_exc
({ vmid
=> "property is missing"})
1200 if !($param->{all
} || $param->{stop
}) && !$param->{vmid
};
1204 sub stop_running_backups
{
1207 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1210 my $task = PVE
::Tools
::upid_decode
($upid);
1212 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1213 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1214 kill(15, $task->{pid
});
1215 # wait max 15 seconds to shut down (else, do nothing for now)
1217 for ($i = 15; $i > 0; $i--) {
1218 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1221 die "stoping backup process $task->{pid} failed\n" if $i == 0;
1230 if ($param->{vmid
}) {
1231 $cmd .= " " . join(' ', PVE
::Tools
::split_list
($param->{vmid
}));
1234 foreach my $p (keys %$param) {
1235 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' ||
1236 $p eq 'dow' || $p eq 'stdout' || $p eq 'enabled';
1237 my $v = $param->{$p};
1238 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
1239 if ($p eq 'exclude-path') {
1240 foreach my $path (split(/\0/, $v || '')) {
1241 $cmd .= " --$p " . PVE
::Tools
::shellquote
($path);
1244 $cmd .= " --$p " . PVE
::Tools
::shellquote
($v) if defined($v) && $v ne '';
1251 # bash completion helpers
1252 sub complete_backup_storage
{
1254 my $cfg = PVE
::Storage
::config
();
1255 my $ids = $cfg->{ids
};
1257 my $nodename = PVE
::INotify
::nodename
();
1260 foreach my $sid (keys %$ids) {
1261 my $scfg = $ids->{$sid};
1262 next if !PVE
::Storage
::storage_check_enabled
($cfg, $sid, $nodename, 1);
1263 next if !$scfg->{content
}->{backup
};