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