]>
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 runnig 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 # Load available plugins
181 my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
182 foreach my $plug (@pve_vzdump_classes) {
183 my $filename = "/usr/share/perl5/$plug.pm";
184 $filename =~ s!::!/!g;
186 eval { require $filename; };
189 push @plugins, $plug;
199 my ($mtype, $msg, $logfd, $syslog) = @_;
201 PVE
::VZDump
::Plugin
::debugmsg
(@_);
205 my ($logfd, $cmdstr, %param) = @_;
209 debugmsg
('info', $line, $logfd);
212 PVE
::Tools
::run_command
($cmdstr, %param, logfunc
=> $logfunc);
218 my $cfg = PVE
::Storage
::config
();
219 my $scfg = PVE
::Storage
::storage_config
($cfg, $storage);
220 my $type = $scfg->{type
};
222 die "can't use storage type '$type' for backup\n"
223 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'
224 || $type eq 'cifs' || $type eq 'cephfs'));
225 die "can't use storage '$storage' for backups - wrong content type\n"
226 if (!$scfg->{content
}->{backup
});
228 PVE
::Storage
::activate_storage
($cfg, $storage);
231 dumpdir
=> PVE
::Storage
::get_backup_dir
($cfg, $storage),
232 maxfiles
=> $scfg->{maxfiles
},
239 my $kb = $size / 1024;
242 return int ($kb) . "KB";
245 my $mb = $size / (1024*1024);
248 return int ($mb) . "MB";
251 return sprintf ("%.2fGB", $gb);
258 my $hours = int ($seconds/3600);
259 $seconds = $seconds - $hours*3600;
260 my $min = int ($seconds/60);
261 $seconds = $seconds - $min*60;
263 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
269 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
287 foreach my $p (split (/:/, $ENV{PATH
})) {
294 die "unable to find command '$bin'\n";
301 foreach my $vmid (@vmids) {
302 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
303 $vmid = int ($vmid); # remove leading zeros
312 sub read_vzdump_defaults
{
314 my $fn = "/etc/vzdump.conf";
318 my $default = $confdesc->{$_}->{default};
319 defined($default) ?
($_ => $default) : ()
324 eval { $raw = PVE
::Tools
::file_get_contents
($fn); };
325 return $defaults if $@;
327 my $conf_schema = { type
=> 'object', properties
=> $confdesc, };
328 my $res = PVE
::JSONSchema
::parse_config
($conf_schema, $fn, $raw);
329 if (my $excludes = $res->{'exclude-path'}) {
330 $res->{'exclude-path'} = PVE
::Tools
::split_args
($excludes);
332 if (defined($res->{mailto
})) {
333 my @mailto = PVE
::Tools
::split_list
($res->{mailto
});
334 $res->{mailto
} = [ @mailto ];
337 foreach my $key (keys %$defaults) {
338 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
345 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
347 my $opts = $self->{opts
};
349 my $mailto = $opts->{mailto
};
351 return if !($mailto && scalar(@$mailto));
353 my $cmdline = $self->{cmdline
};
356 foreach my $task (@$tasklist) {
357 $ecount++ if $task->{state} ne 'ok';
358 chomp $task->{msg
} if $task->{msg
};
359 $task->{backuptime
} = 0 if !$task->{backuptime
};
360 $task->{size
} = 0 if !$task->{size
};
361 $task->{tarfile
} = 'unknown' if !$task->{tarfile
};
362 $task->{hostname
} = "VM $task->{vmid}" if !$task->{hostname
};
364 if ($task->{state} eq 'todo') {
365 $task->{msg
} = 'aborted';
369 my $notify = $opts->{mailnotification
} || 'always';
370 return if (!$ecount && !$err && ($notify eq 'failure'));
372 my $stat = ($ecount || $err) ?
'backup failed' : 'backup successful';
375 $stat .= ": multiple problems";
382 my $hostname = `hostname -f` || PVE
::INotify
::nodename
();
386 my $text = $err ?
"$err\n\n" : '';
387 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
388 foreach my $task (@$tasklist) {
389 my $vmid = $task->{vmid
};
390 if ($task->{state} eq 'ok') {
392 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", $vmid,
394 format_time
($task->{backuptime
}),
395 format_size
($task->{size
}),
398 $text .= sprintf ("%-10s %-6s %10s %8.2fMB %s\n", $vmid,
400 format_time
($task->{backuptime
}),
405 $text .= "\nDetailed backup logs:\n\n";
406 $text .= "$cmdline\n\n";
408 $text .= $detail_pre . "\n" if defined($detail_pre);
409 foreach my $task (@$tasklist) {
410 my $vmid = $task->{vmid
};
411 my $log = $task->{tmplog
};
413 $text .= "$vmid: no log available\n\n";
417 while (my $line = <TMP
>) { $text .= encode8bit
("$vmid: $line"); }
421 $text .= $detail_post if defined($detail_post);
424 my $html = "<html><body>\n";
425 $html .= "<p>" . (escape_html
($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
426 $html .= "<table border=1 cellpadding=3>\n";
427 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
431 foreach my $task (@$tasklist) {
432 my $vmid = $task->{vmid
};
433 my $name = $task->{hostname
};
435 if ($task->{state} eq 'ok') {
437 $ssize += $task->{size
};
439 $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
441 format_time
($task->{backuptime
}),
442 format_size
($task->{size
}),
443 escape_html
($task->{tarfile
}));
445 $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
446 $vmid, $name, format_time
($task->{backuptime
}),
447 escape_html
($task->{msg
}));
451 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
452 format_time
($totaltime), format_size
($ssize));
454 $html .= "</table><br><br>\n";
455 $html .= "Detailed backup logs:<br /><br />\n";
457 $html .= escape_html
($cmdline) . "\n\n";
459 $html .= escape_html
($detail_pre) . "\n" if defined($detail_pre);
460 foreach my $task (@$tasklist) {
461 my $vmid = $task->{vmid
};
462 my $log = $task->{tmplog
};
464 $html .= "$vmid: no log available\n\n";
468 while (my $line = <TMP
>) {
469 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
470 $html .= encode8bit
("$vmid: <font color=red>".
471 escape_html
($line) . "</font>");
473 $html .= encode8bit
("$vmid: " . escape_html
($line));
479 $html .= escape_html
($detail_post) if defined($detail_post);
480 $html .= "</pre></body></html>\n";
483 my $subject = "vzdump backup status ($hostname) : $stat";
485 my $dcconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
486 my $mailfrom = $dcconf->{email_from
} || "root";
488 PVE
::Tools
::sendmail
($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
492 my ($class, $cmdline, $opts, $skiplist) = @_;
498 check_bin
('sendmail');
502 check_bin
('umount');
503 check_bin
('cstream');
504 check_bin
('ionice');
506 if ($opts->{mode
} && $opts->{mode
} eq 'snapshot') {
507 check_bin
('lvcreate');
509 check_bin
('lvremove');
512 my $defaults = read_vzdump_defaults
();
514 my $maxfiles = $opts->{maxfiles
}; # save here, because we overwrite with default
516 $opts->{remove
} = 1 if !defined($opts->{remove
});
518 foreach my $k (keys %$defaults) {
519 next if $k eq 'exclude-path'; # dealt with separately
520 if ($k eq 'dumpdir' || $k eq 'storage') {
521 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir
}) &&
522 !defined ($opts->{storage
});
524 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
528 $opts->{dumpdir
} =~ s
|/+$|| if ($opts->{dumpdir
});
529 $opts->{tmpdir
} =~ s
|/+$|| if ($opts->{tmpdir
});
531 $skiplist = [] if !$skiplist;
532 my $self = bless { cmdline
=> $cmdline, opts
=> $opts, skiplist
=> $skiplist };
534 my $findexcl = $self->{findexcl
} = [];
535 if ($defaults->{'exclude-path'}) {
536 push @$findexcl, @{$defaults->{'exclude-path'}};
539 if ($opts->{'exclude-path'}) {
540 push @$findexcl, @{$opts->{'exclude-path'}};
543 if ($opts->{stdexcludes
}) {
544 push @$findexcl, '/tmp/?*',
549 foreach my $p (@plugins) {
551 my $pd = $p->new ($self);
553 push @{$self->{plugins
}}, $pd;
556 if (!$opts->{dumpdir
} && !$opts->{storage
}) {
557 $opts->{storage
} = 'local';
562 if ($opts->{storage
}) {
565 $info = storage_info
($opts->{storage
});
567 $errors .= "could not get storage information for '$opts->{storage}': $@"
569 $opts->{dumpdir
} = $info->{dumpdir
};
570 $maxfiles = $info->{maxfiles
} if !defined($maxfiles) && defined($info->{maxfiles
});
571 } elsif ($opts->{dumpdir
}) {
572 $errors .= "dumpdir '$opts->{dumpdir}' does not exist"
573 if ! -d
$opts->{dumpdir
};
575 die "internal error";
578 if ($opts->{tmpdir
} && ! -d
$opts->{tmpdir
}) {
579 $errors .= "\n" if $errors;
580 $errors .= "tmpdir '$opts->{tmpdir}' does not exist";
584 eval { $self->sendmail([], 0, $errors); };
585 debugmsg
('err', $@) if $@;
589 $opts->{maxfiles
} = $maxfiles if defined($maxfiles);
598 # Note: df 'available' can be negative, and percentage set to '-'
600 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
606 if (my ($fsid, $fstype, undef, $mp) = $line =~
607 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
616 eval { PVE
::Tools
::run_command
($cmd, errfunc
=> sub {}, outfunc
=> $parser); };
623 my ($self, $upid) = @_;
627 my $maxwait = $self->{opts
}->{lockwait
} || $self->{lockwait
};
629 die "missimg UPID" if !$upid; # should not happen
631 if (!open (SERVER_FLCK
, ">>$lockfile")) {
632 debugmsg
('err', "can't open lock on file '$lockfile' - $!", undef, 1);
633 die "can't open lock on file '$lockfile' - $!";
636 if (!flock (SERVER_FLCK
, LOCK_EX
|LOCK_NB
)) {
639 debugmsg
('err', "can't aquire lock '$lockfile' (wait = 0)", undef, 1);
640 die "can't aquire lock '$lockfile' (wait = 0)";
643 debugmsg
('info', "trying to get global lock - waiting...", undef, 1);
646 alarm ($maxwait * 60);
648 local $SIG{ALRM
} = sub { alarm (0); die "got timeout\n"; };
650 if (!flock (SERVER_FLCK
, LOCK_EX
)) {
663 debugmsg
('err', "can't aquire lock '$lockfile' - $err", undef, 1);
664 die "can't aquire lock '$lockfile' - $err";
667 debugmsg
('info', "got global lock", undef, 1);
670 PVE
::Tools
::file_set_contents
($pidfile, $upid);
673 sub run_hook_script
{
674 my ($self, $phase, $task, $logfd) = @_;
676 my $opts = $self->{opts
};
678 my $script = $opts->{script
};
682 my $cmd = "$script $phase";
684 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
688 # set immutable opts directly (so they are available in all phases)
689 $ENV{STOREID
} = $opts->{storage
} if $opts->{storage
};
690 $ENV{DUMPDIR
} = $opts->{dumpdir
} if $opts->{dumpdir
};
692 foreach my $ek (qw(vmtype hostname tarfile logfile)) {
693 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
696 run_command
($logfd, $cmd);
699 sub compressor_info
{
701 my $opt_compress = $opts->{compress
};
703 if (!$opt_compress || $opt_compress eq '0') {
705 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
706 return ('lzop', 'lzo');
707 } elsif ($opt_compress eq 'gzip') {
708 if ($opts->{pigz
} > 0) {
709 my $pigz_threads = $opts->{pigz
};
710 if ($pigz_threads == 1) {
711 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
712 $pigz_threads = int(($cpuinfo->{cpus
} + 1)/2);
714 return ("pigz -p ${pigz_threads}", 'gz');
716 return ('gzip', 'gz');
719 die "internal error - unknown compression option '$opt_compress'";
723 sub get_backup_file_list
{
724 my ($dir, $bkname, $exclude_fn) = @_;
727 foreach my $fn (<$dir/${bkname
}-*>) {
728 next if $exclude_fn && $fn eq $exclude_fn;
729 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?)))$!) {
730 $fn = "$dir/$1"; # untaint
731 my $t = timelocal
($7, $6, $5, $4, $3 - 1, $2);
732 push @$bklist, [$fn, $t];
739 sub exec_backup_task
{
740 my ($self, $task) = @_;
742 my $opts = $self->{opts
};
744 my $vmid = $task->{vmid
};
745 my $plugin = $task->{plugin
};
747 my $vmstarttime = time ();
756 die "unable to find VM '$vmid'\n" if !$plugin;
758 # for now we deny backups of a running ha managed service in *stop* mode
759 # as it interferes with the HA stack (started services should not stop).
760 if ($opts->{mode
} eq 'stop' &&
761 PVE
::HA
::Config
::vm_is_ha_managed
($vmid, 'started'))
763 die "Cannot execute a backup with stop mode on a HA managed and".
764 " enabled Service. Use snapshot mode or disable the Service.\n";
767 my $vmtype = $plugin->type();
769 my $tmplog = "$logdir/$vmtype-$vmid.log";
771 my $bkname = "vzdump-$vmtype-$vmid";
772 my $basename = $bkname . strftime
("-%Y_%m_%d-%H_%M_%S", localtime());
774 my $maxfiles = $opts->{maxfiles
};
776 if ($maxfiles && !$opts->{remove
}) {
777 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname);
778 die "only $maxfiles backup(s) allowed - please consider to remove old backup files.\n"
779 if scalar(@$bklist) >= $maxfiles;
782 my $logfile = $task->{logfile
} = "$opts->{dumpdir}/$basename.log";
784 my $ext = $vmtype eq 'qemu' ?
'.vma' : '.tar';
785 my ($comp, $comp_ext) = compressor_info
($opts);
786 if ($comp && $comp_ext) {
787 $ext .= ".${comp_ext}";
790 if ($opts->{stdout
}) {
791 $task->{tarfile
} = '-';
793 my $tarfile = $task->{tarfile
} = "$opts->{dumpdir}/$basename$ext";
794 $task->{tmptar
} = $task->{tarfile
};
795 $task->{tmptar
} =~ s/\.[^\.]+$/\.dat/;
796 unlink $task->{tmptar
};
799 $task->{vmtype
} = $vmtype;
801 if ($opts->{tmpdir
}) {
802 $task->{tmpdir
} = "$opts->{tmpdir}/vzdumptmp$$";
804 # dumpdir is posix? then use it as temporary dir
805 my $info = get_mount_info
($opts->{dumpdir
});
806 if ($vmtype eq 'qemu' ||
807 grep ($_ eq $info->{fstype
}, @posix_filesystems)) {
808 $task->{tmpdir
} = "$opts->{dumpdir}/$basename.tmp";
810 $task->{tmpdir
} = "/var/tmp/vzdumptmp$$";
811 debugmsg
('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
812 "using $task->{tmpdir} for temporary files", $logfd);
816 rmtree
$task->{tmpdir
};
817 mkdir $task->{tmpdir
};
818 -d
$task->{tmpdir
} ||
819 die "unable to create temporary directory '$task->{tmpdir}'";
821 $logfd = IO
::File-
>new (">$tmplog") ||
822 die "unable to create log file '$tmplog'";
824 $task->{dumpdir
} = $opts->{dumpdir
};
825 $task->{storeid
} = $opts->{storage
};
826 $task->{tmplog
} = $tmplog;
830 debugmsg
('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
831 debugmsg
('info', "Backup started at " . strftime
("%F %H:%M:%S", localtime()));
833 $plugin->set_logfd ($logfd);
835 # test is VM is running
836 my ($running, $status_text) = $plugin->vm_status ($vmid);
838 debugmsg
('info', "status = ${status_text}", $logfd);
840 # lock VM (prevent config changes)
841 $plugin->lock_vm ($vmid);
843 $cleanup->{unlock
} = 1;
847 my $mode = $running ?
$task->{mode
} : 'stop';
849 if ($mode eq 'snapshot') {
850 my %saved_task = %$task;
851 eval { $plugin->prepare ($task, $vmid, $mode); };
853 die $err if $err !~ m/^mode failure/;
854 debugmsg
('info', $err, $logfd);
855 debugmsg
('info', "trying 'suspend' mode instead", $logfd);
856 $mode = 'suspend'; # so prepare is called again below
857 %$task = %saved_task;
861 $cleanup->{prepared
} = 1;
863 $task->{mode
} = $mode;
865 debugmsg
('info', "backup mode: $mode", $logfd);
867 debugmsg
('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
870 debugmsg
('info', "ionice priority: $opts->{ionice}", $logfd);
872 if ($mode eq 'stop') {
874 $plugin->prepare ($task, $vmid, $mode);
876 $self->run_hook_script ('backup-start', $task, $logfd);
879 debugmsg
('info', "stopping vm", $logfd);
880 $vmstoptime = time ();
881 $self->run_hook_script ('pre-stop', $task, $logfd);
882 $plugin->stop_vm ($task, $vmid);
883 $cleanup->{restart
} = 1;
887 } elsif ($mode eq 'suspend') {
889 $plugin->prepare ($task, $vmid, $mode);
891 $self->run_hook_script ('backup-start', $task, $logfd);
893 if ($vmtype eq 'lxc') {
895 $plugin->copy_data_phase1($task, $vmid);
898 debugmsg
('info', "suspend vm", $logfd);
899 $vmstoptime = time ();
900 $self->run_hook_script ('pre-stop', $task, $logfd);
901 $plugin->suspend_vm ($task, $vmid);
902 $cleanup->{resume
} = 1;
904 if ($vmtype eq 'lxc') {
906 $plugin->copy_data_phase2($task, $vmid);
908 debugmsg
('info', "resume vm", $logfd);
909 $cleanup->{resume
} = 0;
910 $self->run_hook_script('pre-restart', $task, $logfd);
911 $plugin->resume_vm($task, $vmid);
912 $self->run_hook_script('post-restart', $task, $logfd);
913 my $delay = time () - $vmstoptime;
914 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
917 } elsif ($mode eq 'snapshot') {
919 $self->run_hook_script ('backup-start', $task, $logfd);
921 my $snapshot_count = $task->{snapshot_count
} || 0;
923 $self->run_hook_script ('pre-stop', $task, $logfd);
925 if ($snapshot_count > 1) {
926 debugmsg
('info', "suspend vm to make snapshot", $logfd);
927 $vmstoptime = time ();
928 $plugin->suspend_vm ($task, $vmid);
929 $cleanup->{resume
} = 1;
932 $plugin->snapshot ($task, $vmid);
934 $self->run_hook_script ('pre-restart', $task, $logfd);
936 if ($snapshot_count > 1) {
937 debugmsg
('info', "resume vm", $logfd);
938 $cleanup->{resume
} = 0;
939 $plugin->resume_vm ($task, $vmid);
940 my $delay = time () - $vmstoptime;
941 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
944 $self->run_hook_script ('post-restart', $task, $logfd);
947 die "internal error - unknown mode '$mode'\n";
950 # assemble archive image
951 $plugin->assemble ($task, $vmid);
955 if ($opts->{stdout
}) {
956 debugmsg
('info', "sending archive to stdout", $logfd);
957 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
958 $self->run_hook_script ('backup-end', $task, $logfd);
962 debugmsg
('info', "creating archive '$task->{tarfile}'", $logfd);
963 $plugin->archive($task, $vmid, $task->{tmptar
}, $comp);
965 rename ($task->{tmptar
}, $task->{tarfile
}) ||
966 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
969 $task->{size
} = (-s
$task->{tarfile
}) || 0;
970 my $cs = format_size
($task->{size
});
971 debugmsg
('info', "archive file size: $cs", $logfd);
975 if ($maxfiles && $opts->{remove
}) {
976 my $bklist = get_backup_file_list
($opts->{dumpdir
}, $bkname, $task->{tarfile
});
977 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
979 while (scalar (@$bklist) >= $maxfiles) {
980 my $d = pop @$bklist;
981 debugmsg
('info', "delete old backup '$d->[0]'", $logfd);
984 $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
989 $self->run_hook_script ('backup-end', $task, $logfd);
996 if ($cleanup->{unlock
}) {
997 eval { $plugin->unlock_vm ($vmid); };
1001 if ($cleanup->{prepared
}) {
1002 # only call cleanup when necessary (when prepare was executed)
1003 eval { $plugin->cleanup ($task, $vmid) };
1007 eval { $plugin->set_logfd (undef); };
1010 if ($cleanup->{resume
} || $cleanup->{restart
}) {
1012 $self->run_hook_script ('pre-restart', $task, $logfd);
1013 if ($cleanup->{resume
}) {
1014 debugmsg
('info', "resume vm", $logfd);
1015 $plugin->resume_vm ($task, $vmid);
1017 my $running = $plugin->vm_status($vmid);
1019 debugmsg
('info', "restarting vm", $logfd);
1020 $plugin->start_vm ($task, $vmid);
1023 $self->run_hook_script ('post-restart', $task, $logfd);
1029 my $delay = time () - $vmstoptime;
1030 debugmsg
('info', "vm is online again after $delay seconds", $logfd);
1035 eval { unlink $task->{tmptar
} if $task->{tmptar
} && -f
$task->{tmptar
}; };
1038 eval { rmtree
$task->{tmpdir
} if $task->{tmpdir
} && -d
$task->{tmpdir
}; };
1041 my $delay = $task->{backuptime
} = time () - $vmstarttime;
1044 $task->{state} = 'err';
1045 $task->{msg
} = $err;
1046 debugmsg
('err', "Backup of VM $vmid failed - $err", $logfd, 1);
1047 debugmsg
('info', "Failed at " . strftime
("%F %H:%M:%S", localtime()));
1049 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1052 $task->{state} = 'ok';
1053 my $tstr = format_time
($delay);
1054 debugmsg
('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
1055 debugmsg
('info', "Backup finished at " . strftime
("%F %H:%M:%S", localtime()));
1058 close ($logfd) if $logfd;
1060 if ($task->{tmplog
} && $task->{logfile
}) {
1061 system {'cp'} 'cp', $task->{tmplog
}, $task->{logfile
};
1064 eval { $self->run_hook_script ('log-end', $task); };
1066 die $err if $err && $err =~ m/^interrupted by signal$/;
1070 my ($self, $rpcenv, $authuser) = @_;
1072 my $opts = $self->{opts
};
1074 debugmsg
('info', "starting new backup job: $self->{cmdline}", undef, 1);
1075 debugmsg
('info', "skip external VMs: " . join(', ', @{$self->{skiplist
}}))
1076 if scalar(@{$self->{skiplist
}});
1081 foreach my $plugin (@{$self->{plugins
}}) {
1082 my $vmlist = $plugin->vmlist();
1083 foreach my $vmid (sort @$vmlist) {
1084 next if grep { $_ eq $vmid } @{$opts->{exclude
}};
1085 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
1086 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin, mode
=> $opts->{mode
} };
1090 foreach my $vmid (sort @{$opts->{vmids
}}) {
1092 foreach my $pg (@{$self->{plugins
}}) {
1093 my $vmlist = $pg->vmlist();
1094 if (grep { $_ eq $vmid } @$vmlist) {
1099 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
1100 push @$tasklist, { vmid
=> $vmid, state => 'todo', plugin
=> $plugin, mode
=> $opts->{mode
} };
1104 # Use in-memory files for the outer hook logs to pass them to sendmail.
1105 my $job_start_log = '';
1106 my $job_end_log = '';
1107 open my $job_start_fd, '>', \
$job_start_log;
1108 open my $job_end_fd, '>', \
$job_end_log;
1110 my $starttime = time();
1114 $self->run_hook_script ('job-start', undef, $job_start_fd);
1116 foreach my $task (@$tasklist) {
1117 $self->exec_backup_task ($task);
1118 $errcount += 1 if $task->{state} ne 'ok';
1121 $self->run_hook_script ('job-end', undef, $job_end_fd);
1125 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
1128 debugmsg
('err', "Backup job failed - $err", undef, 1);
1131 debugmsg
('info', "Backup job finished with errors", undef, 1);
1133 debugmsg
('info', "Backup job finished successfully", undef, 1);
1137 close $job_start_fd;
1140 my $totaltime = time() - $starttime;
1142 eval { $self->sendmail ($tasklist, $totaltime, undef, $job_start_log, $job_end_log); };
1143 debugmsg
('err', $@) if $@;
1147 die "job errors\n" if $errcount;
1155 return defined($confdesc->{$key});
1158 # add JSON properties for create and set function
1159 sub json_config_properties
{
1162 foreach my $opt (keys %$confdesc) {
1163 $prop->{$opt} = $confdesc->{$opt};
1169 sub verify_vzdump_parameters
{
1170 my ($param, $check_missing) = @_;
1172 raise_param_exc
({ all
=> "option conflicts with option 'vmid'"})
1173 if $param->{all
} && $param->{vmid
};
1175 raise_param_exc
({ exclude
=> "option conflicts with option 'vmid'"})
1176 if $param->{exclude
} && $param->{vmid
};
1178 $param->{all
} = 1 if defined($param->{exclude
});
1180 warn "option 'size' is deprecated and will be removed in a future " .
1181 "release, please update your script/configuration!\n"
1182 if defined($param->{size
});
1184 return if !$check_missing;
1186 raise_param_exc
({ vmid
=> "property is missing"})
1187 if !($param->{all
} || $param->{stop
}) && !$param->{vmid
};
1191 sub stop_running_backups
{
1194 my $upid = PVE
::Tools
::file_read_firstline
($pidfile);
1197 my $task = PVE
::Tools
::upid_decode
($upid);
1199 if (PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
}) &&
1200 PVE
::ProcFSTools
::read_proc_starttime
($task->{pid
}) == $task->{pstart
}) {
1201 kill(15, $task->{pid
});
1202 # wait max 15 seconds to shut down (else, do nothing for now)
1204 for ($i = 15; $i > 0; $i--) {
1205 last if !PVE
::ProcFSTools
::check_process_running
(($task->{pid
}, $task->{pstart
}));
1208 die "stoping backup process $task->{pid} failed\n" if $i == 0;
1217 if ($param->{vmid
}) {
1218 $cmd .= " " . join(' ', PVE
::Tools
::split_list
($param->{vmid
}));
1221 foreach my $p (keys %$param) {
1222 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' ||
1223 $p eq 'dow' || $p eq 'stdout' || $p eq 'enabled';
1224 my $v = $param->{$p};
1225 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
1226 if ($p eq 'exclude-path') {
1227 foreach my $path (split(/\0/, $v || '')) {
1228 $cmd .= " --$p " . PVE
::Tools
::shellquote
($path);
1231 $cmd .= " --$p " . PVE
::Tools
::shellquote
($v) if defined($v) && $v ne '';
1238 # bash completion helpers
1239 sub complete_backup_storage
{
1241 my $cfg = PVE
::Storage
::config
();
1242 my $ids = $cfg->{ids
};
1244 my $nodename = PVE
::INotify
::nodename
();
1247 foreach my $sid (keys %$ids) {
1248 my $scfg = $ids->{$sid};
1249 next if !PVE
::Storage
::storage_check_enabled
($cfg, $sid, $nodename, 1);
1250 next if !$scfg->{content
}->{backup
};