]> git.proxmox.com Git - pve-manager.git/blame - PVE/VZDump.pm
api: node/config: allow to return only a specific config property
[pve-manager.git] / PVE / VZDump.pm
CommitLineData
aaeeeebe
DM
1package PVE::VZDump;
2
aaeeeebe
DM
3use strict;
4use warnings;
5use Fcntl ':flock';
31aef761 6use PVE::Exception qw(raise_param_exc);
aaeeeebe
DM
7use IO::File;
8use IO::Select;
9use IPC::Open3;
aaeeeebe 10use File::Path;
98e84b16 11use PVE::RPCEnvironment;
4a4051d8
DM
12use PVE::Storage;
13use PVE::Cluster qw(cfs_read_file);
3ac3653e 14use PVE::DataCenterConfig;
e2b5eb29 15use POSIX qw(strftime);
aaeeeebe 16use Time::Local;
ac27b58d 17use PVE::JSONSchema qw(get_standard_option);
10a9a736 18use PVE::HA::Env::PVE2;
2de3ee58 19use PVE::HA::Config;
a5c94797 20use PVE::VZDump::Plugin;
2424074e 21use PVE::VZDump::Common;
aaeeeebe
DM
22
23my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
24
25my $lockfile = '/var/run/vzdump.lock';
8682f6fc 26my $pidfile = '/var/run/vzdump.pid';
aaeeeebe
DM
27my $logdir = '/var/log/vzdump';
28
dafb6246 29my @plugins = qw();
aaeeeebe 30
2424074e 31my $confdesc = PVE::VZDump::Common::get_confdesc();
cc61ea36 32
aaeeeebe 33# Load available plugins
8187f6b0
DM
34my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
35foreach my $plug (@pve_vzdump_classes) {
36 my $filename = "/usr/share/perl5/$plug.pm";
37 $filename =~ s!::!/!g;
38 if (-f $filename) {
39 eval { require $filename; };
40 if (!$@) {
41 $plug->import ();
42 push @plugins, $plug;
43 } else {
c76d0106 44 die $@;
8187f6b0
DM
45 }
46 }
aaeeeebe
DM
47}
48
49# helper functions
50
aaeeeebe
DM
51sub debugmsg {
52 my ($mtype, $msg, $logfd, $syslog) = @_;
53
a5c94797 54 PVE::VZDump::Plugin::debugmsg(@_);
aaeeeebe
DM
55}
56
57sub run_command {
58 my ($logfd, $cmdstr, %param) = @_;
59
7f910306 60 my $logfunc = sub {
4a4051d8 61 my $line = shift;
4a4051d8 62 debugmsg ('info', $line, $logfd);
aaeeeebe
DM
63 };
64
7f910306 65 PVE::Tools::run_command($cmdstr, %param, logfunc => $logfunc);
aaeeeebe
DM
66}
67
68sub storage_info {
69 my $storage = shift;
70
bbcfdc08 71 my $cfg = PVE::Storage::config();
4a4051d8 72 my $scfg = PVE::Storage::storage_config($cfg, $storage);
aaeeeebe 73 my $type = $scfg->{type};
60e049c2
TM
74
75 die "can't use storage type '$type' for backup\n"
6d09915c 76 if (!($type eq 'dir' || $type eq 'nfs' || $type eq 'glusterfs'
59abc310 77 || $type eq 'cifs' || $type eq 'cephfs'));
60e049c2 78 die "can't use storage '$storage' for backups - wrong content type\n"
aaeeeebe
DM
79 if (!$scfg->{content}->{backup});
80
4a4051d8 81 PVE::Storage::activate_storage($cfg, $storage);
aaeeeebe
DM
82
83 return {
30edfad9 84 dumpdir => PVE::Storage::get_backup_dir($cfg, $storage),
19d5c0f2 85 maxfiles => $scfg->{maxfiles},
aaeeeebe
DM
86 };
87}
88
89sub format_size {
90 my $size = shift;
91
92 my $kb = $size / 1024;
93
94 if ($kb < 1024) {
95 return int ($kb) . "KB";
96 }
97
98 my $mb = $size / (1024*1024);
99
100 if ($mb < 1024) {
101 return int ($mb) . "MB";
102 } else {
103 my $gb = $mb / 1024;
104 return sprintf ("%.2fGB", $gb);
60e049c2 105 }
aaeeeebe
DM
106}
107
108sub format_time {
109 my $seconds = shift;
110
111 my $hours = int ($seconds/3600);
112 $seconds = $seconds - $hours*3600;
113 my $min = int ($seconds/60);
114 $seconds = $seconds - $min*60;
115
116 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
117}
118
119sub encode8bit {
120 my ($str) = @_;
121
122 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
123
124 return $str;
125}
126
127sub escape_html {
128 my ($str) = @_;
129
130 $str =~ s/&/&amp;/g;
131 $str =~ s/</&lt;/g;
132 $str =~ s/>/&gt;/g;
133
134 return $str;
135}
136
137sub check_bin {
138 my ($bin) = @_;
139
140 foreach my $p (split (/:/, $ENV{PATH})) {
141 my $fn = "$p/$bin";
142 if (-x $fn) {
143 return $fn;
144 }
145 }
146
147 die "unable to find command '$bin'\n";
148}
149
150sub check_vmids {
151 my (@vmids) = @_;
152
153 my $res = [];
154 foreach my $vmid (@vmids) {
155 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
156 $vmid = int ($vmid); # remove leading zeros
4a4051d8 157 next if !$vmid;
aaeeeebe
DM
158 push @$res, $vmid;
159 }
160
161 return $res;
162}
163
164
165sub read_vzdump_defaults {
166
167 my $fn = "/etc/vzdump.conf";
168
cc61ea36 169 my $defaults = {
1ab98f05
WB
170 map {
171 my $default = $confdesc->{$_}->{default};
172 defined($default) ? ($_ => $default) : ()
173 } keys %$confdesc
aaeeeebe
DM
174 };
175
cc61ea36
TL
176 my $raw;
177 eval { $raw = PVE::Tools::file_get_contents($fn); };
178 return $defaults if $@;
aaeeeebe 179
cc61ea36
TL
180 my $conf_schema = { type => 'object', properties => $confdesc, };
181 my $res = PVE::JSONSchema::parse_config($conf_schema, $fn, $raw);
6368bbd4
WB
182 if (my $excludes = $res->{'exclude-path'}) {
183 $res->{'exclude-path'} = PVE::Tools::split_args($excludes);
184 }
74b47fd8
FG
185 if (defined($res->{mailto})) {
186 my @mailto = PVE::Tools::split_list($res->{mailto});
187 $res->{mailto} = [ @mailto ];
188 }
cc61ea36
TL
189
190 foreach my $key (keys %$defaults) {
e94fa5cb 191 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
aaeeeebe 192 }
aaeeeebe
DM
193
194 return $res;
195}
196
6ec9de44 197sub sendmail {
44b21574 198 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
aaeeeebe
DM
199
200 my $opts = $self->{opts};
201
202 my $mailto = $opts->{mailto};
203
4a4051d8 204 return if !($mailto && scalar(@$mailto));
aaeeeebe
DM
205
206 my $cmdline = $self->{cmdline};
207
208 my $ecount = 0;
209 foreach my $task (@$tasklist) {
210 $ecount++ if $task->{state} ne 'ok';
211 chomp $task->{msg} if $task->{msg};
212 $task->{backuptime} = 0 if !$task->{backuptime};
213 $task->{size} = 0 if !$task->{size};
214 $task->{tarfile} = 'unknown' if !$task->{tarfile};
215 $task->{hostname} = "VM $task->{vmid}" if !$task->{hostname};
216
217 if ($task->{state} eq 'todo') {
218 $task->{msg} = 'aborted';
219 }
220 }
221
02e59759
DM
222 my $notify = $opts->{mailnotification} || 'always';
223 return if (!$ecount && !$err && ($notify eq 'failure'));
8b4b4860 224
6ec9de44 225 my $stat = ($ecount || $err) ? 'backup failed' : 'backup successful';
403761c4
WB
226 if ($err) {
227 if ($err =~ /\n/) {
228 $stat .= ": multiple problems";
229 } else {
230 $stat .= ": $err";
231 $err = undef;
232 }
233 }
aaeeeebe 234
4a4051d8 235 my $hostname = `hostname -f` || PVE::INotify::nodename();
aaeeeebe
DM
236 chomp $hostname;
237
aaeeeebe 238 # text part
403761c4
WB
239 my $text = $err ? "$err\n\n" : '';
240 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
aaeeeebe
DM
241 foreach my $task (@$tasklist) {
242 my $vmid = $task->{vmid};
243 if ($task->{state} eq 'ok') {
244
7a0a8e67
TL
245 $text .= sprintf ("%-10s %-6s %10s %10s %s\n", $vmid,
246 $task->{state},
aaeeeebe
DM
247 format_time($task->{backuptime}),
248 format_size ($task->{size}),
249 $task->{tarfile});
250 } else {
7a0a8e67
TL
251 $text .= sprintf ("%-10s %-6s %10s %8.2fMB %s\n", $vmid,
252 $task->{state},
aaeeeebe
DM
253 format_time($task->{backuptime}),
254 0, '-');
255 }
256 }
7a0a8e67 257
0da2260f 258 $text .= "\nDetailed backup logs:\n\n";
7a0a8e67 259 $text .= "$cmdline\n\n";
aaeeeebe 260
44b21574 261 $text .= $detail_pre . "\n" if defined($detail_pre);
aaeeeebe
DM
262 foreach my $task (@$tasklist) {
263 my $vmid = $task->{vmid};
264 my $log = $task->{tmplog};
265 if (!$log) {
7a0a8e67 266 $text .= "$vmid: no log available\n\n";
aaeeeebe
DM
267 next;
268 }
269 open (TMP, "$log");
7a0a8e67 270 while (my $line = <TMP>) { $text .= encode8bit ("$vmid: $line"); }
aaeeeebe 271 close (TMP);
7a0a8e67 272 $text .= "\n";
aaeeeebe 273 }
44b21574 274 $text .= $detail_post if defined($detail_post);
aaeeeebe 275
aaeeeebe 276 # html part
7a0a8e67 277 my $html = "<html><body>\n";
403761c4 278 $html .= "<p>" . (escape_html($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
7a0a8e67
TL
279 $html .= "<table border=1 cellpadding=3>\n";
280 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
aaeeeebe
DM
281
282 my $ssize = 0;
283
284 foreach my $task (@$tasklist) {
285 my $vmid = $task->{vmid};
286 my $name = $task->{hostname};
287
288 if ($task->{state} eq 'ok') {
289
290 $ssize += $task->{size};
291
7a0a8e67 292 $html .= sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
aaeeeebe
DM
293 $vmid, $name,
294 format_time($task->{backuptime}),
295 format_size ($task->{size}),
296 escape_html ($task->{tarfile}));
297 } else {
7a0a8e67
TL
298 $html .= sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
299 $vmid, $name, format_time($task->{backuptime}),
aaeeeebe
DM
300 escape_html ($task->{msg}));
301 }
302 }
303
7a0a8e67 304 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
aaeeeebe
DM
305 format_time ($totaltime), format_size ($ssize));
306
7a0a8e67
TL
307 $html .= "</table><br><br>\n";
308 $html .= "Detailed backup logs:<br /><br />\n";
309 $html .= "<pre>\n";
310 $html .= escape_html($cmdline) . "\n\n";
aaeeeebe 311
44b21574 312 $html .= escape_html($detail_pre) . "\n" if defined($detail_pre);
aaeeeebe
DM
313 foreach my $task (@$tasklist) {
314 my $vmid = $task->{vmid};
315 my $log = $task->{tmplog};
316 if (!$log) {
7a0a8e67 317 $html .= "$vmid: no log available\n\n";
aaeeeebe
DM
318 next;
319 }
320 open (TMP, "$log");
321 while (my $line = <TMP>) {
322 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
7a0a8e67
TL
323 $html .= encode8bit ("$vmid: <font color=red>".
324 escape_html ($line) . "</font>");
aaeeeebe 325 } else {
7a0a8e67 326 $html .= encode8bit ("$vmid: " . escape_html ($line));
aaeeeebe
DM
327 }
328 }
329 close (TMP);
7a0a8e67 330 $html .= "\n";
aaeeeebe 331 }
44b21574 332 $html .= escape_html($detail_post) if defined($detail_post);
7a0a8e67
TL
333 $html .= "</pre></body></html>\n";
334 # end html part
aaeeeebe 335
7a0a8e67 336 my $subject = "vzdump backup status ($hostname) : $stat";
aaeeeebe 337
7a0a8e67
TL
338 my $dcconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
339 my $mailfrom = $dcconf->{email_from} || "root";
aaeeeebe 340
7a0a8e67 341 PVE::Tools::sendmail($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
aaeeeebe
DM
342};
343
344sub new {
a7e42354 345 my ($class, $cmdline, $opts, $skiplist) = @_;
aaeeeebe
DM
346
347 mkpath $logdir;
348
349 check_bin ('cp');
350 check_bin ('df');
351 check_bin ('sendmail');
352 check_bin ('rsync');
353 check_bin ('tar');
354 check_bin ('mount');
355 check_bin ('umount');
356 check_bin ('cstream');
357 check_bin ('ionice');
358
47664cbe 359 if ($opts->{mode} && $opts->{mode} eq 'snapshot') {
aaeeeebe
DM
360 check_bin ('lvcreate');
361 check_bin ('lvs');
362 check_bin ('lvremove');
363 }
364
365 my $defaults = read_vzdump_defaults();
366
84ad4385
DM
367 my $maxfiles = $opts->{maxfiles}; # save here, because we overwrite with default
368
899b8373
DM
369 $opts->{remove} = 1 if !defined($opts->{remove});
370
aaeeeebe 371 foreach my $k (keys %$defaults) {
b1f09117 372 next if $k eq 'exclude-path'; # dealt with separately
aaeeeebe
DM
373 if ($k eq 'dumpdir' || $k eq 'storage') {
374 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
375 !defined ($opts->{storage});
376 } else {
377 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
378 }
379 }
380
aaeeeebe
DM
381 $opts->{dumpdir} =~ s|/+$|| if ($opts->{dumpdir});
382 $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
383
a7e42354
DM
384 $skiplist = [] if !$skiplist;
385 my $self = bless { cmdline => $cmdline, opts => $opts, skiplist => $skiplist };
aaeeeebe 386
45f16a06 387 my $findexcl = $self->{findexcl} = [];
f4a8bab4 388 if ($defaults->{'exclude-path'}) {
45f16a06 389 push @$findexcl, @{$defaults->{'exclude-path'}};
f4a8bab4
DM
390 }
391
aaeeeebe 392 if ($opts->{'exclude-path'}) {
45f16a06 393 push @$findexcl, @{$opts->{'exclude-path'}};
aaeeeebe
DM
394 }
395
396 if ($opts->{stdexcludes}) {
e42ae622 397 push @$findexcl, '/tmp/?*',
45f16a06 398 '/var/tmp/?*',
0568e342 399 '/var/run/?*.pid';
aaeeeebe
DM
400 }
401
402 foreach my $p (@plugins) {
403
404 my $pd = $p->new ($self);
405
406 push @{$self->{plugins}}, $pd;
aaeeeebe
DM
407 }
408
409 if (!$opts->{dumpdir} && !$opts->{storage}) {
19d5c0f2 410 $opts->{storage} = 'local';
aaeeeebe
DM
411 }
412
403761c4
WB
413 my $errors = '';
414
aaeeeebe 415 if ($opts->{storage}) {
1e4583d5 416 my $info = eval { storage_info ($opts->{storage}) };
c3b58274
FG
417 $errors .= "could not get storage information for '$opts->{storage}': $@"
418 if ($@);
aaeeeebe 419 $opts->{dumpdir} = $info->{dumpdir};
1e4583d5 420 $maxfiles //= $info->{maxfiles};
aaeeeebe 421 } elsif ($opts->{dumpdir}) {
403761c4 422 $errors .= "dumpdir '$opts->{dumpdir}' does not exist"
aaeeeebe
DM
423 if ! -d $opts->{dumpdir};
424 } else {
60e049c2 425 die "internal error";
aaeeeebe
DM
426 }
427
428 if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
403761c4
WB
429 $errors .= "\n" if $errors;
430 $errors .= "tmpdir '$opts->{tmpdir}' does not exist";
431 }
432
433 if ($errors) {
434 eval { $self->sendmail([], 0, $errors); };
435 debugmsg ('err', $@) if $@;
436 die "$errors\n";
aaeeeebe
DM
437 }
438
84ad4385 439 $opts->{maxfiles} = $maxfiles if defined($maxfiles);
899b8373 440
aaeeeebe
DM
441 return $self;
442
443}
444
aaeeeebe
DM
445sub get_mount_info {
446 my ($dir) = @_;
447
8572d646
DM
448 # Note: df 'available' can be negative, and percentage set to '-'
449
d93d0459 450 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
aaeeeebe 451
d93d0459 452 my $res;
aaeeeebe 453
d93d0459
DM
454 my $parser = sub {
455 my $line = shift;
8572d646
DM
456 if (my ($fsid, $fstype, undef, $mp) = $line =~
457 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
d93d0459
DM
458 $res = {
459 device => $fsid,
460 fstype => $fstype,
461 mountpoint => $mp,
462 };
463 }
aaeeeebe 464 };
d93d0459
DM
465
466 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
467 warn $@ if $@;
468
469 return $res;
aaeeeebe
DM
470}
471
aaeeeebe 472sub getlock {
eab837c4 473 my ($self, $upid) = @_;
aaeeeebe 474
8682f6fc 475 my $fh;
60e049c2 476
aaeeeebe 477 my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
60e049c2 478
eab837c4
DM
479 die "missimg UPID" if !$upid; # should not happen
480
aaeeeebe
DM
481 if (!open (SERVER_FLCK, ">>$lockfile")) {
482 debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
6ec9de44 483 die "can't open lock on file '$lockfile' - $!";
aaeeeebe
DM
484 }
485
eab837c4 486 if (!flock (SERVER_FLCK, LOCK_EX|LOCK_NB)) {
aaeeeebe 487
eab837c4 488 if (!$maxwait) {
76189130
TL
489 debugmsg ('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
490 die "can't acquire lock '$lockfile' (wait = 0)";
eab837c4 491 }
aaeeeebe 492
eab837c4 493 debugmsg('info', "trying to get global lock - waiting...", undef, 1);
aaeeeebe 494
eab837c4
DM
495 eval {
496 alarm ($maxwait * 60);
60e049c2 497
eab837c4 498 local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
aaeeeebe 499
eab837c4
DM
500 if (!flock (SERVER_FLCK, LOCK_EX)) {
501 my $err = $!;
502 close (SERVER_FLCK);
503 alarm (0);
504 die "$err\n";
505 }
aaeeeebe 506 alarm (0);
eab837c4 507 };
aaeeeebe 508 alarm (0);
60e049c2 509
eab837c4 510 my $err = $@;
60e049c2 511
eab837c4 512 if ($err) {
76189130
TL
513 debugmsg ('err', "can't acquire lock '$lockfile' - $err", undef, 1);
514 die "can't acquire lock '$lockfile' - $err";
eab837c4 515 }
aaeeeebe 516
eab837c4 517 debugmsg('info', "got global lock", undef, 1);
aaeeeebe
DM
518 }
519
eab837c4 520 PVE::Tools::file_set_contents($pidfile, $upid);
aaeeeebe
DM
521}
522
523sub run_hook_script {
524 my ($self, $phase, $task, $logfd) = @_;
525
526 my $opts = $self->{opts};
527
528 my $script = $opts->{script};
529
530 return if !$script;
531
532 my $cmd = "$script $phase";
533
534 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
535
536 local %ENV;
537
28272ca2
DM
538 # set immutable opts directly (so they are available in all phases)
539 $ENV{STOREID} = $opts->{storage} if $opts->{storage};
540 $ENV{DUMPDIR} = $opts->{dumpdir} if $opts->{dumpdir};
541
542 foreach my $ek (qw(vmtype hostname tarfile logfile)) {
aaeeeebe
DM
543 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
544 }
545
546 run_command ($logfd, $cmd);
547}
548
d7550e09 549sub compressor_info {
778d5b6d
TL
550 my ($opts) = @_;
551 my $opt_compress = $opts->{compress};
d7550e09
DM
552
553 if (!$opt_compress || $opt_compress eq '0') {
554 return undef;
555 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
556 return ('lzop', 'lzo');
557 } elsif ($opt_compress eq 'gzip') {
778d5b6d 558 if ($opts->{pigz} > 0) {
8555b100
TL
559 my $pigz_threads = $opts->{pigz};
560 if ($pigz_threads == 1) {
561 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
562 $pigz_threads = int(($cpuinfo->{cpus} + 1)/2);
563 }
778d5b6d
TL
564 return ("pigz -p ${pigz_threads}", 'gz');
565 } else {
e953f92a 566 return ('gzip --rsyncable', 'gz');
778d5b6d 567 }
d7550e09
DM
568 } else {
569 die "internal error - unknown compression option '$opt_compress'";
570 }
571}
899b8373
DM
572
573sub get_backup_file_list {
574 my ($dir, $bkname, $exclude_fn) = @_;
575
576 my $bklist = [];
577 foreach my $fn (<$dir/${bkname}-*>) {
578 next if $exclude_fn && $fn eq $exclude_fn;
757fd3d5 579 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?)))$!) {
899b8373 580 $fn = "$dir/$1"; # untaint
998e4eeb 581 my $t = timelocal ($7, $6, $5, $4, $3 - 1, $2);
899b8373
DM
582 push @$bklist, [$fn, $t];
583 }
584 }
585
586 return $bklist;
587}
60e049c2 588
aaeeeebe
DM
589sub exec_backup_task {
590 my ($self, $task) = @_;
60e049c2 591
aaeeeebe
DM
592 my $opts = $self->{opts};
593
594 my $vmid = $task->{vmid};
595 my $plugin = $task->{plugin};
596
597 my $vmstarttime = time ();
60e049c2 598
aaeeeebe
DM
599 my $logfd;
600
601 my $cleanup = {};
602
4e0947c8
TL
603 my $log_vm_online_again = sub {
604 return if !defined($task->{vmstoptime});
605 $task->{vmconttime} //= time();
606 my $delay = $task->{vmconttime} - $task->{vmstoptime};
607 debugmsg ('info', "guest is online again after $delay seconds", $logfd);
608 };
aaeeeebe
DM
609
610 eval {
611 die "unable to find VM '$vmid'\n" if !$plugin;
612
2de3ee58 613 # for now we deny backups of a running ha managed service in *stop* mode
83ec8f81 614 # as it interferes with the HA stack (started services should not stop).
2de3ee58 615 if ($opts->{mode} eq 'stop' &&
83ec8f81 616 PVE::HA::Config::vm_is_ha_managed($vmid, 'started'))
2de3ee58
TL
617 {
618 die "Cannot execute a backup with stop mode on a HA managed and".
619 " enabled Service. Use snapshot mode or disable the Service.\n";
620 }
621
aaeeeebe
DM
622 my $vmtype = $plugin->type();
623
624 my $tmplog = "$logdir/$vmtype-$vmid.log";
625
aaeeeebe 626 my $bkname = "vzdump-$vmtype-$vmid";
e2b5eb29 627 my $basename = $bkname . strftime("-%Y_%m_%d-%H_%M_%S", localtime());
aaeeeebe 628
899b8373
DM
629 my $maxfiles = $opts->{maxfiles};
630
631 if ($maxfiles && !$opts->{remove}) {
632 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
6c09101a
OB
633 die "There is a max backup limit of ($maxfiles) enforced by the".
634 " target storage or the vzdump parameters.".
635 " Either increase the limit or delete old backup(s).\n"
899b8373
DM
636 if scalar(@$bklist) >= $maxfiles;
637 }
638
aaeeeebe
DM
639 my $logfile = $task->{logfile} = "$opts->{dumpdir}/$basename.log";
640
757fd3d5 641 my $ext = $vmtype eq 'qemu' ? '.vma' : '.tar';
778d5b6d 642 my ($comp, $comp_ext) = compressor_info($opts);
d7550e09
DM
643 if ($comp && $comp_ext) {
644 $ext .= ".${comp_ext}";
645 }
aaeeeebe
DM
646
647 if ($opts->{stdout}) {
648 $task->{tarfile} = '-';
649 } else {
650 my $tarfile = $task->{tarfile} = "$opts->{dumpdir}/$basename$ext";
651 $task->{tmptar} = $task->{tarfile};
652 $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
653 unlink $task->{tmptar};
654 }
655
656 $task->{vmtype} = $vmtype;
657
658 if ($opts->{tmpdir}) {
60e049c2 659 $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp$$";
aaeeeebe
DM
660 } else {
661 # dumpdir is posix? then use it as temporary dir
5dc86eb8 662 my $info = get_mount_info($opts->{dumpdir});
60e049c2 663 if ($vmtype eq 'qemu' ||
aaeeeebe
DM
664 grep ($_ eq $info->{fstype}, @posix_filesystems)) {
665 $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
666 } else {
667 $task->{tmpdir} = "/var/tmp/vzdumptmp$$";
668 debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
669 "using $task->{tmpdir} for temporary files", $logfd);
670 }
671 }
672
673 rmtree $task->{tmpdir};
674 mkdir $task->{tmpdir};
675 -d $task->{tmpdir} ||
676 die "unable to create temporary directory '$task->{tmpdir}'";
677
678 $logfd = IO::File->new (">$tmplog") ||
679 die "unable to create log file '$tmplog'";
680
681 $task->{dumpdir} = $opts->{dumpdir};
ff00abe6 682 $task->{storeid} = $opts->{storage};
aaeeeebe
DM
683 $task->{tmplog} = $tmplog;
684
685 unlink $logfile;
686
29f26f6d
DJ
687 debugmsg ('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
688 debugmsg ('info', "Backup started at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
689
690 $plugin->set_logfd ($logfd);
691
692 # test is VM is running
693 my ($running, $status_text) = $plugin->vm_status ($vmid);
694
695 debugmsg ('info', "status = ${status_text}", $logfd);
696
697 # lock VM (prevent config changes)
698 $plugin->lock_vm ($vmid);
699
700 $cleanup->{unlock} = 1;
701
702 # prepare
703
6acb632a 704 my $mode = $running ? $task->{mode} : 'stop';
aaeeeebe
DM
705
706 if ($mode eq 'snapshot') {
707 my %saved_task = %$task;
708 eval { $plugin->prepare ($task, $vmid, $mode); };
709 if (my $err = $@) {
710 die $err if $err !~ m/^mode failure/;
711 debugmsg ('info', $err, $logfd);
712 debugmsg ('info', "trying 'suspend' mode instead", $logfd);
713 $mode = 'suspend'; # so prepare is called again below
60e049c2 714 %$task = %saved_task;
aaeeeebe
DM
715 }
716 }
717
6acb632a
WB
718 $cleanup->{prepared} = 1;
719
aaeeeebe
DM
720 $task->{mode} = $mode;
721
722 debugmsg ('info', "backup mode: $mode", $logfd);
723
724 debugmsg ('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
725 if $opts->{bwlimit};
726
727 debugmsg ('info', "ionice priority: $opts->{ionice}", $logfd);
728
729 if ($mode eq 'stop') {
730
731 $plugin->prepare ($task, $vmid, $mode);
732
733 $self->run_hook_script ('backup-start', $task, $logfd);
734
735 if ($running) {
736 debugmsg ('info', "stopping vm", $logfd);
4e0947c8 737 $task->{vmstoptime} = time();
aaeeeebe
DM
738 $self->run_hook_script ('pre-stop', $task, $logfd);
739 $plugin->stop_vm ($task, $vmid);
740 $cleanup->{restart} = 1;
741 }
60e049c2 742
aaeeeebe
DM
743
744 } elsif ($mode eq 'suspend') {
745
746 $plugin->prepare ($task, $vmid, $mode);
747
748 $self->run_hook_script ('backup-start', $task, $logfd);
749
8187f6b0
DM
750 if ($vmtype eq 'lxc') {
751 # pre-suspend rsync
752 $plugin->copy_data_phase1($task, $vmid);
753 }
754
aaeeeebe 755 debugmsg ('info', "suspend vm", $logfd);
4e0947c8 756 $task->{vmstoptime} = time ();
aaeeeebe
DM
757 $self->run_hook_script ('pre-stop', $task, $logfd);
758 $plugin->suspend_vm ($task, $vmid);
759 $cleanup->{resume} = 1;
760
8187f6b0
DM
761 if ($vmtype eq 'lxc') {
762 # post-suspend rsync
763 $plugin->copy_data_phase2($task, $vmid);
764
765 debugmsg ('info', "resume vm", $logfd);
766 $cleanup->{resume} = 0;
767 $self->run_hook_script('pre-restart', $task, $logfd);
768 $plugin->resume_vm($task, $vmid);
d5047243 769 $self->run_hook_script('post-restart', $task, $logfd);
4e0947c8 770 $log_vm_online_again->();
8187f6b0 771 }
60e049c2 772
aaeeeebe
DM
773 } elsif ($mode eq 'snapshot') {
774
c5be0f8c
DM
775 $self->run_hook_script ('backup-start', $task, $logfd);
776
aaeeeebe
DM
777 my $snapshot_count = $task->{snapshot_count} || 0;
778
779 $self->run_hook_script ('pre-stop', $task, $logfd);
780
781 if ($snapshot_count > 1) {
782 debugmsg ('info', "suspend vm to make snapshot", $logfd);
4e0947c8 783 $task->{vmstoptime} = time ();
aaeeeebe
DM
784 $plugin->suspend_vm ($task, $vmid);
785 $cleanup->{resume} = 1;
786 }
787
788 $plugin->snapshot ($task, $vmid);
789
790 $self->run_hook_script ('pre-restart', $task, $logfd);
791
792 if ($snapshot_count > 1) {
793 debugmsg ('info', "resume vm", $logfd);
794 $cleanup->{resume} = 0;
795 $plugin->resume_vm ($task, $vmid);
4e0947c8 796 $log_vm_online_again->();
aaeeeebe
DM
797 }
798
d5047243
FG
799 $self->run_hook_script ('post-restart', $task, $logfd);
800
aaeeeebe
DM
801 } else {
802 die "internal error - unknown mode '$mode'\n";
803 }
804
805 # assemble archive image
806 $plugin->assemble ($task, $vmid);
60e049c2
TM
807
808 # produce archive
aaeeeebe
DM
809
810 if ($opts->{stdout}) {
811 debugmsg ('info', "sending archive to stdout", $logfd);
d7550e09 812 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
813 $self->run_hook_script ('backup-end', $task, $logfd);
814 return;
815 }
816
817 debugmsg ('info', "creating archive '$task->{tarfile}'", $logfd);
d7550e09 818 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
819
820 rename ($task->{tmptar}, $task->{tarfile}) ||
821 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
822
823 # determine size
824 $task->{size} = (-s $task->{tarfile}) || 0;
60e049c2 825 my $cs = format_size ($task->{size});
aaeeeebe
DM
826 debugmsg ('info', "archive file size: $cs", $logfd);
827
828 # purge older backup
829
899b8373
DM
830 if ($maxfiles && $opts->{remove}) {
831 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname, $task->{tarfile});
832 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
aaeeeebe 833
899b8373
DM
834 while (scalar (@$bklist) >= $maxfiles) {
835 my $d = pop @$bklist;
aaeeeebe
DM
836 debugmsg ('info', "delete old backup '$d->[0]'", $logfd);
837 unlink $d->[0];
838 my $logfn = $d->[0];
757fd3d5 839 $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
aaeeeebe
DM
840 unlink $logfn;
841 }
842 }
843
844 $self->run_hook_script ('backup-end', $task, $logfd);
845 };
846 my $err = $@;
847
848 if ($plugin) {
849 # clean-up
850
851 if ($cleanup->{unlock}) {
852 eval { $plugin->unlock_vm ($vmid); };
853 warn $@ if $@;
854 }
855
6acb632a 856 if ($cleanup->{prepared}) {
ca2605e7
DM
857 # only call cleanup when necessary (when prepare was executed)
858 eval { $plugin->cleanup ($task, $vmid) };
859 warn $@ if $@;
860 }
aaeeeebe
DM
861
862 eval { $plugin->set_logfd (undef); };
863 warn $@ if $@;
864
60e049c2
TM
865 if ($cleanup->{resume} || $cleanup->{restart}) {
866 eval {
aaeeeebe
DM
867 $self->run_hook_script ('pre-restart', $task, $logfd);
868 if ($cleanup->{resume}) {
869 debugmsg ('info', "resume vm", $logfd);
870 $plugin->resume_vm ($task, $vmid);
871 } else {
757fd3d5
DM
872 my $running = $plugin->vm_status($vmid);
873 if (!$running) {
874 debugmsg ('info', "restarting vm", $logfd);
875 $plugin->start_vm ($task, $vmid);
876 }
d5047243
FG
877 }
878 $self->run_hook_script ('post-restart', $task, $logfd);
aaeeeebe
DM
879 };
880 my $err = $@;
881 if ($err) {
882 warn $err;
883 } else {
4e0947c8 884 $log_vm_online_again->();
aaeeeebe
DM
885 }
886 }
887 }
888
889 eval { unlink $task->{tmptar} if $task->{tmptar} && -f $task->{tmptar}; };
890 warn $@ if $@;
891
fe6643b6 892 eval { rmtree $task->{tmpdir} if $task->{tmpdir} && -d $task->{tmpdir}; };
aaeeeebe
DM
893 warn $@ if $@;
894
895 my $delay = $task->{backuptime} = time () - $vmstarttime;
896
897 if ($err) {
898 $task->{state} = 'err';
899 $task->{msg} = $err;
900 debugmsg ('err', "Backup of VM $vmid failed - $err", $logfd, 1);
29f26f6d 901 debugmsg ('info', "Failed at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
902
903 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
904
905 } else {
906 $task->{state} = 'ok';
907 my $tstr = format_time ($delay);
908 debugmsg ('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
29f26f6d 909 debugmsg ('info', "Backup finished at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
910 }
911
912 close ($logfd) if $logfd;
60e049c2 913
aaeeeebe 914 if ($task->{tmplog} && $task->{logfile}) {
6cd97500 915 system {'cp'} 'cp', $task->{tmplog}, $task->{logfile};
aaeeeebe
DM
916 }
917
918 eval { $self->run_hook_script ('log-end', $task); };
919
920 die $err if $err && $err =~ m/^interrupted by signal$/;
921}
922
923sub exec_backup {
d7550e09 924 my ($self, $rpcenv, $authuser) = @_;
aaeeeebe
DM
925
926 my $opts = $self->{opts};
927
928 debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
a7e42354
DM
929 debugmsg ('info', "skip external VMs: " . join(', ', @{$self->{skiplist}}))
930 if scalar(@{$self->{skiplist}});
60e049c2 931
aaeeeebe
DM
932 my $tasklist = [];
933
934 if ($opts->{all}) {
935 foreach my $plugin (@{$self->{plugins}}) {
936 my $vmlist = $plugin->vmlist();
937 foreach my $vmid (sort @$vmlist) {
938 next if grep { $_ eq $vmid } @{$opts->{exclude}};
98e84b16 939 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
6acb632a 940 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin, mode => $opts->{mode} };
aaeeeebe
DM
941 }
942 }
943 } else {
944 foreach my $vmid (sort @{$opts->{vmids}}) {
945 my $plugin;
946 foreach my $pg (@{$self->{plugins}}) {
947 my $vmlist = $pg->vmlist();
948 if (grep { $_ eq $vmid } @$vmlist) {
949 $plugin = $pg;
950 last;
951 }
952 }
98e84b16 953 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
6acb632a 954 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin, mode => $opts->{mode} };
aaeeeebe
DM
955 }
956 }
957
44b21574
WB
958 # Use in-memory files for the outer hook logs to pass them to sendmail.
959 my $job_start_log = '';
960 my $job_end_log = '';
961 open my $job_start_fd, '>', \$job_start_log;
962 open my $job_end_fd, '>', \$job_end_log;
963
aaeeeebe
DM
964 my $starttime = time();
965 my $errcount = 0;
966 eval {
967
44b21574 968 $self->run_hook_script ('job-start', undef, $job_start_fd);
aaeeeebe
DM
969
970 foreach my $task (@$tasklist) {
971 $self->exec_backup_task ($task);
972 $errcount += 1 if $task->{state} ne 'ok';
973 }
974
44b21574 975 $self->run_hook_script ('job-end', undef, $job_end_fd);
aaeeeebe
DM
976 };
977 my $err = $@;
978
44b21574 979 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
aaeeeebe
DM
980
981 if ($err) {
982 debugmsg ('err', "Backup job failed - $err", undef, 1);
983 } else {
984 if ($errcount) {
985 debugmsg ('info', "Backup job finished with errors", undef, 1);
986 } else {
61ca4432 987 debugmsg ('info', "Backup job finished successfully", undef, 1);
aaeeeebe
DM
988 }
989 }
990
44b21574
WB
991 close $job_start_fd;
992 close $job_end_fd;
993
aaeeeebe
DM
994 my $totaltime = time() - $starttime;
995
44b21574 996 eval { $self->sendmail ($tasklist, $totaltime, undef, $job_start_log, $job_end_log); };
aaeeeebe 997 debugmsg ('err', $@) if $@;
4a4051d8
DM
998
999 die $err if $err;
1000
60e049c2 1001 die "job errors\n" if $errcount;
8682f6fc
WL
1002
1003 unlink $pidfile;
aaeeeebe
DM
1004}
1005
ac27b58d 1006
47664cbe
DM
1007sub option_exists {
1008 my $key = shift;
1009 return defined($confdesc->{$key});
1010}
1011
31aef761
DM
1012sub verify_vzdump_parameters {
1013 my ($param, $check_missing) = @_;
1014
1015 raise_param_exc({ all => "option conflicts with option 'vmid'"})
eab837c4 1016 if $param->{all} && $param->{vmid};
31aef761
DM
1017
1018 raise_param_exc({ exclude => "option conflicts with option 'vmid'"})
1019 if $param->{exclude} && $param->{vmid};
1020
f3376261
TM
1021 raise_param_exc({ pool => "option conflicts with option 'vmid'"})
1022 if $param->{pool} && $param->{vmid};
1023
1024 $param->{all} = 1 if (defined($param->{exclude}) && !$param->{pool});
31aef761 1025
e2a2525e
FG
1026 warn "option 'size' is deprecated and will be removed in a future " .
1027 "release, please update your script/configuration!\n"
1028 if defined($param->{size});
1029
31aef761
DM
1030 return if !$check_missing;
1031
1032 raise_param_exc({ vmid => "property is missing"})
f3376261 1033 if !($param->{all} || $param->{stop} || $param->{pool}) && !$param->{vmid};
8682f6fc
WL
1034
1035}
1036
eab837c4 1037sub stop_running_backups {
8682f6fc
WL
1038 my($self) = @_;
1039
eab837c4
DM
1040 my $upid = PVE::Tools::file_read_firstline($pidfile);
1041 return if !$upid;
8682f6fc 1042
eab837c4 1043 my $task = PVE::Tools::upid_decode($upid);
8682f6fc 1044
60e049c2 1045 if (PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart}) &&
eab837c4
DM
1046 PVE::ProcFSTools::read_proc_starttime($task->{pid}) == $task->{pstart}) {
1047 kill(15, $task->{pid});
1048 # wait max 15 seconds to shut down (else, do nothing for now)
1049 my $i;
1050 for ($i = 15; $i > 0; $i--) {
1051 last if !PVE::ProcFSTools::check_process_running(($task->{pid}, $task->{pstart}));
1052 sleep (1);
1053 }
76189130 1054 die "stopping backup process $task->{pid} failed\n" if $i == 0;
8682f6fc 1055 }
31aef761
DM
1056}
1057
aaeeeebe 10581;