]> git.proxmox.com Git - pve-manager.git/blame - PVE/VZDump.pm
ui: mdev selector: avoid separate gettext for "Avail"
[pve-manager.git] / PVE / VZDump.pm
CommitLineData
aaeeeebe
DM
1package PVE::VZDump;
2
aaeeeebe
DM
3use strict;
4use warnings;
df2d3636 5
3f488b61 6use Clone;
aaeeeebe 7use Fcntl ':flock';
bbd4cdd8 8use File::Basename;
df2d3636 9use File::Path;
aaeeeebe
DM
10use IO::File;
11use IO::Select;
12use IPC::Open3;
e2b5eb29 13use POSIX qw(strftime);
aaeeeebe 14use Time::Local;
df2d3636
TL
15
16use PVE::Cluster qw(cfs_read_file);
17use PVE::DataCenterConfig;
18use PVE::Exception qw(raise_param_exc);
2de3ee58 19use PVE::HA::Config;
df2d3636
TL
20use PVE::HA::Env::PVE2;
21use PVE::JSONSchema qw(get_standard_option);
22use PVE::RPCEnvironment;
23use PVE::Storage;
2424074e 24use PVE::VZDump::Common;
df2d3636 25use PVE::VZDump::Plugin;
05447e04 26use PVE::Tools qw(extract_param split_list);
5c4da4c3 27use PVE::API2Tools;
aaeeeebe
DM
28
29my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
30
31my $lockfile = '/var/run/vzdump.lock';
8682f6fc 32my $pidfile = '/var/run/vzdump.pid';
aaeeeebe
DM
33my $logdir = '/var/log/vzdump';
34
dafb6246 35my @plugins = qw();
aaeeeebe 36
2424074e 37my $confdesc = PVE::VZDump::Common::get_confdesc();
cc61ea36 38
3f488b61
FE
39my $confdesc_for_defaults = Clone::clone($confdesc);
40delete $confdesc_for_defaults->{$_}->{requires} for qw(notes-template protected);
41
aaeeeebe 42# Load available plugins
8187f6b0
DM
43my @pve_vzdump_classes = qw(PVE::VZDump::QemuServer PVE::VZDump::LXC);
44foreach my $plug (@pve_vzdump_classes) {
45 my $filename = "/usr/share/perl5/$plug.pm";
46 $filename =~ s!::!/!g;
47 if (-f $filename) {
48 eval { require $filename; };
49 if (!$@) {
50 $plug->import ();
51 push @plugins, $plug;
52 } else {
c76d0106 53 die $@;
8187f6b0
DM
54 }
55 }
aaeeeebe
DM
56}
57
58# helper functions
59
aaeeeebe
DM
60sub debugmsg {
61 my ($mtype, $msg, $logfd, $syslog) = @_;
62
a5c94797 63 PVE::VZDump::Plugin::debugmsg(@_);
aaeeeebe
DM
64}
65
66sub run_command {
67 my ($logfd, $cmdstr, %param) = @_;
68
7f910306 69 my $logfunc = sub {
4a4051d8 70 my $line = shift;
4a4051d8 71 debugmsg ('info', $line, $logfd);
aaeeeebe
DM
72 };
73
7f910306 74 PVE::Tools::run_command($cmdstr, %param, logfunc => $logfunc);
aaeeeebe
DM
75}
76
facf65a6
FE
77my $verify_notes_template = sub {
78 my ($template) = @_;
79
80 die "contains a line feed\n" if $template =~ /\n/;
81
82 my @problematic = ();
83 while ($template =~ /\\(.)/g) {
84 my $char = $1;
85 push @problematic, "escape sequence '\\$char' at char " . (pos($template) - 2)
86 if $char !~ /^[n\\]$/;
87 }
88
89 while ($template =~ /\{\{([^\s{}]+)\}\}/g) {
90 my $var = $1;
91 push @problematic, "variable '$var' at char " . (pos($template) - length($var))
92 if $var !~ /^(cluster|guestname|node|vmid)$/;
93 }
94
95 die "found unknown: " . join(', ', @problematic) . "\n" if scalar(@problematic);
96};
97
e01438a7
FE
98my $generate_notes = sub {
99 my ($notes_template, $task) = @_;
100
facf65a6
FE
101 $verify_notes_template->($notes_template);
102
e01438a7 103 my $info = {
2078e359
FE
104 cluster => PVE::Cluster::get_clinfo()->{cluster}->{name} // 'standalone node',
105 guestname => $task->{hostname} // "VM $task->{vmid}", # is always set for CTs
e01438a7
FE
106 node => PVE::INotify::nodename(),
107 vmid => $task->{vmid},
108 };
109
31213d61
FE
110 my $unescape = sub {
111 my ($char) = @_;
112 return '\\' if $char eq '\\';
113 return "\n" if $char eq 'n';
114 die "unexpected escape character '$char'\n";
e01438a7
FE
115 };
116
31213d61 117 $notes_template =~ s/\\(.)/$unescape->($1)/eg;
e01438a7
FE
118
119 my $vars = join('|', keys $info->%*);
4ed6e1b1 120 $notes_template =~ s/\{\{($vars)\}\}/$info->{$1}/g;
e01438a7
FE
121
122 return $notes_template;
123};
124
1c56bcf3
FE
125my $parse_prune_backups_maxfiles = sub {
126 my ($param, $kind) = @_;
127
128 my $maxfiles = delete $param->{maxfiles};
129 my $prune_backups = $param->{'prune-backups'};
130
fb6871fc 131 debugmsg('warn', "both 'maxfiles' and 'prune-backups' defined as ${kind} - ignoring 'maxfiles'")
1c56bcf3
FE
132 if defined($maxfiles) && defined($prune_backups);
133
134 if (defined($prune_backups)) {
ecc08c34 135 return if ref($prune_backups) eq 'HASH'; # already parsed
1c56bcf3
FE
136 $param->{'prune-backups'} = PVE::JSONSchema::parse_property_string(
137 'prune-backups',
138 $prune_backups
139 );
140 } elsif (defined($maxfiles)) {
141 if ($maxfiles) {
142 $param->{'prune-backups'} = { 'keep-last' => $maxfiles };
143 } else {
144 $param->{'prune-backups'} = { 'keep-all' => 1 };
145 }
146 }
147};
148
aaeeeebe
DM
149sub storage_info {
150 my $storage = shift;
151
bbcfdc08 152 my $cfg = PVE::Storage::config();
4a4051d8 153 my $scfg = PVE::Storage::storage_config($cfg, $storage);
aaeeeebe 154 my $type = $scfg->{type};
60e049c2 155
60e049c2 156 die "can't use storage '$storage' for backups - wrong content type\n"
aaeeeebe
DM
157 if (!$scfg->{content}->{backup});
158
3a805f8d
FE
159 my $info = {
160 scfg => $scfg,
3a805f8d
FE
161 };
162
e6946086
FE
163 $info->{'prune-backups'} = PVE::JSONSchema::parse_property_string('prune-backups', $scfg->{'prune-backups'})
164 if defined($scfg->{'prune-backups'});
165
1a87db9e 166 if ($type eq 'pbs') {
3a805f8d 167 $info->{pbs} = 1;
1a87db9e 168 } else {
3a805f8d 169 $info->{dumpdir} = PVE::Storage::get_backup_dir($cfg, $storage);
1a87db9e 170 }
3a805f8d
FE
171
172 return $info;
aaeeeebe
DM
173}
174
175sub format_size {
176 my $size = shift;
177
178 my $kb = $size / 1024;
179
180 if ($kb < 1024) {
181 return int ($kb) . "KB";
182 }
183
184 my $mb = $size / (1024*1024);
aaeeeebe
DM
185 if ($mb < 1024) {
186 return int ($mb) . "MB";
9c3a51ee
TL
187 }
188 my $gb = $mb / 1024;
189 if ($gb < 1024) {
aaeeeebe 190 return sprintf ("%.2fGB", $gb);
60e049c2 191 }
9c3a51ee
TL
192 my $tb = $gb / 1024;
193 return sprintf ("%.2fTB", $tb);
aaeeeebe
DM
194}
195
196sub format_time {
197 my $seconds = shift;
198
199 my $hours = int ($seconds/3600);
200 $seconds = $seconds - $hours*3600;
201 my $min = int ($seconds/60);
202 $seconds = $seconds - $min*60;
203
204 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
205}
206
207sub encode8bit {
208 my ($str) = @_;
209
210 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
211
212 return $str;
213}
214
215sub escape_html {
216 my ($str) = @_;
217
218 $str =~ s/&/&amp;/g;
219 $str =~ s/</&lt;/g;
220 $str =~ s/>/&gt;/g;
221
222 return $str;
223}
224
225sub check_bin {
226 my ($bin) = @_;
227
228 foreach my $p (split (/:/, $ENV{PATH})) {
229 my $fn = "$p/$bin";
230 if (-x $fn) {
231 return $fn;
232 }
233 }
234
235 die "unable to find command '$bin'\n";
236}
237
238sub check_vmids {
239 my (@vmids) = @_;
240
241 my $res = [];
50ba40ec 242 for my $vmid (sort {$a <=> $b} @vmids) {
aaeeeebe
DM
243 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
244 $vmid = int ($vmid); # remove leading zeros
4a4051d8 245 next if !$vmid;
aaeeeebe
DM
246 push @$res, $vmid;
247 }
248
249 return $res;
250}
251
252
253sub read_vzdump_defaults {
254
255 my $fn = "/etc/vzdump.conf";
256
cc61ea36 257 my $defaults = {
1ab98f05
WB
258 map {
259 my $default = $confdesc->{$_}->{default};
260 defined($default) ? ($_ => $default) : ()
3f488b61 261 } keys %$confdesc_for_defaults
aaeeeebe 262 };
dd5d80f5 263 $parse_prune_backups_maxfiles->($defaults, "defaults in VZDump schema");
aaeeeebe 264
cc61ea36
TL
265 my $raw;
266 eval { $raw = PVE::Tools::file_get_contents($fn); };
267 return $defaults if $@;
aaeeeebe 268
3f488b61 269 my $conf_schema = { type => 'object', properties => $confdesc_for_defaults };
cc61ea36 270 my $res = PVE::JSONSchema::parse_config($conf_schema, $fn, $raw);
6368bbd4
WB
271 if (my $excludes = $res->{'exclude-path'}) {
272 $res->{'exclude-path'} = PVE::Tools::split_args($excludes);
273 }
74b47fd8 274 if (defined($res->{mailto})) {
05447e04 275 my @mailto = split_list($res->{mailto});
74b47fd8
FG
276 $res->{mailto} = [ @mailto ];
277 }
dd5d80f5 278 $parse_prune_backups_maxfiles->($res, "options in '$fn'");
cc61ea36
TL
279
280 foreach my $key (keys %$defaults) {
e94fa5cb 281 $res->{$key} = $defaults->{$key} if !defined($res->{$key});
aaeeeebe 282 }
aaeeeebe 283
f1dd7629
FE
284 if (defined($res->{storage}) && defined($res->{dumpdir})) {
285 debugmsg('warn', "both 'storage' and 'dumpdir' defined in '$fn' - ignoring 'dumpdir'");
286 delete $res->{dumpdir};
287 }
288
aaeeeebe
DM
289 return $res;
290}
291
ce84a950 292use constant MAX_MAIL_SIZE => 1024*1024;
6ec9de44 293sub sendmail {
44b21574 294 my ($self, $tasklist, $totaltime, $err, $detail_pre, $detail_post) = @_;
aaeeeebe
DM
295
296 my $opts = $self->{opts};
297
298 my $mailto = $opts->{mailto};
299
4a4051d8 300 return if !($mailto && scalar(@$mailto));
aaeeeebe
DM
301
302 my $cmdline = $self->{cmdline};
303
304 my $ecount = 0;
305 foreach my $task (@$tasklist) {
306 $ecount++ if $task->{state} ne 'ok';
307 chomp $task->{msg} if $task->{msg};
308 $task->{backuptime} = 0 if !$task->{backuptime};
309 $task->{size} = 0 if !$task->{size};
6cba1855 310 $task->{target} = 'unknown' if !$task->{target};
aaeeeebe
DM
311 $task->{hostname} = "VM $task->{vmid}" if !$task->{hostname};
312
313 if ($task->{state} eq 'todo') {
314 $task->{msg} = 'aborted';
315 }
316 }
317
02e59759
DM
318 my $notify = $opts->{mailnotification} || 'always';
319 return if (!$ecount && !$err && ($notify eq 'failure'));
8b4b4860 320
6ec9de44 321 my $stat = ($ecount || $err) ? 'backup failed' : 'backup successful';
403761c4
WB
322 if ($err) {
323 if ($err =~ /\n/) {
324 $stat .= ": multiple problems";
325 } else {
326 $stat .= ": $err";
327 $err = undef;
328 }
329 }
aaeeeebe 330
4a4051d8 331 my $hostname = `hostname -f` || PVE::INotify::nodename();
aaeeeebe
DM
332 chomp $hostname;
333
aaeeeebe 334 # text part
403761c4 335 my $text = $err ? "$err\n\n" : '';
2cc64d0e
DJ
336 my $namelength = 20;
337 $text .= sprintf (
338 "%-10s %-${namelength}s %-6s %10s %10s %s\n",
339 qw(VMID NAME STATUS TIME SIZE FILENAME)
340 );
aaeeeebe 341 foreach my $task (@$tasklist) {
2cc64d0e
DJ
342 my $name = substr($task->{hostname}, 0, $namelength);
343 my $successful = $task->{state} eq 'ok';
344 my $size = $successful ? format_size ($task->{size}) : 0;
345 my $filename = $successful ? $task->{target} : '-';
346 my $size_fmt = $successful ? "%10s": "%8.2fMB";
347 $text .= sprintf(
348 "%-10s %-${namelength}s %-6s %10s $size_fmt %s\n",
349 $task->{vmid},
350 $name,
351 $task->{state},
352 format_time($task->{backuptime}),
353 $size,
354 $filename,
355 );
aaeeeebe 356 }
7a0a8e67 357
ce84a950
DJ
358 my $text_log_part;
359 $text_log_part .= "\nDetailed backup logs:\n\n";
360 $text_log_part .= "$cmdline\n\n";
aaeeeebe 361
ce84a950 362 $text_log_part .= $detail_pre . "\n" if defined($detail_pre);
aaeeeebe
DM
363 foreach my $task (@$tasklist) {
364 my $vmid = $task->{vmid};
365 my $log = $task->{tmplog};
366 if (!$log) {
ce84a950 367 $text_log_part .= "$vmid: no log available\n\n";
aaeeeebe
DM
368 next;
369 }
5620e576
TL
370 if (open (my $TMP, '<', "$log")) {
371 while (my $line = <$TMP>) {
ce84a950
DJ
372 next if $line =~ /^status: \d+/; # not useful in mails
373 $text_log_part .= encode8bit ("$vmid: $line");
374 }
5620e576 375 close ($TMP);
ce84a950
DJ
376 } else {
377 $text_log_part .= "$vmid: Could not open log file\n\n";
378 }
ce84a950 379 $text_log_part .= "\n";
aaeeeebe 380 }
ce84a950 381 $text_log_part .= $detail_post if defined($detail_post);
aaeeeebe 382
aaeeeebe 383 # html part
7a0a8e67 384 my $html = "<html><body>\n";
403761c4 385 $html .= "<p>" . (escape_html($err) =~ s/\n/<br>/gr) . "</p>\n" if $err;
7a0a8e67
TL
386 $html .= "<table border=1 cellpadding=3>\n";
387 $html .= "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
aaeeeebe
DM
388
389 my $ssize = 0;
aaeeeebe
DM
390 foreach my $task (@$tasklist) {
391 my $vmid = $task->{vmid};
392 my $name = $task->{hostname};
393
394 if ($task->{state} eq 'ok') {
aaeeeebe
DM
395 $ssize += $task->{size};
396
1353489e
TL
397 $html .= sprintf (
398 "<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
399 $vmid,
400 $name,
401 format_time($task->{backuptime}),
402 format_size ($task->{size}),
403 escape_html ($task->{target}),
404 );
aaeeeebe 405 } else {
1353489e
TL
406 $html .= sprintf (
407 "<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
408 $vmid,
409 $name,
410 format_time($task->{backuptime}),
411 escape_html ($task->{msg}),
412 );
aaeeeebe
DM
413 }
414 }
415
7a0a8e67 416 $html .= sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
aaeeeebe
DM
417 format_time ($totaltime), format_size ($ssize));
418
ce84a950
DJ
419 $html .= "\n</table><br><br>\n";
420 my $html_log_part;
421 $html_log_part .= "Detailed backup logs:<br /><br />\n";
422 $html_log_part .= "<pre>\n";
423 $html_log_part .= escape_html($cmdline) . "\n\n";
aaeeeebe 424
ce84a950 425 $html_log_part .= escape_html($detail_pre) . "\n" if defined($detail_pre);
aaeeeebe
DM
426 foreach my $task (@$tasklist) {
427 my $vmid = $task->{vmid};
428 my $log = $task->{tmplog};
429 if (!$log) {
ce84a950 430 $html_log_part .= "$vmid: no log available\n\n";
aaeeeebe
DM
431 next;
432 }
5620e576
TL
433 if (open (my $TMP, '<', "$log")) {
434 while (my $line = <$TMP>) {
ce84a950
DJ
435 next if $line =~ /^status: \d+/; # not useful in mails
436 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
437 $html_log_part .= encode8bit ("$vmid: <font color=red>".
438 escape_html ($line) . "</font>");
439 } else {
440 $html_log_part .= encode8bit ("$vmid: " . escape_html ($line));
441 }
aaeeeebe 442 }
5620e576 443 close ($TMP);
ce84a950
DJ
444 } else {
445 $html_log_part .= "$vmid: Could not open log file\n\n";
aaeeeebe 446 }
ce84a950 447 $html_log_part .= "\n";
aaeeeebe 448 }
ce84a950
DJ
449 $html_log_part .= escape_html($detail_post) if defined($detail_post);
450 $html_log_part .= "</pre>";
213e0eb2 451 my $html_end = "\n</body></html>\n";
7a0a8e67 452 # end html part
aaeeeebe 453
ce84a950 454 if (length($text) + length($text_log_part) +
213e0eb2
FE
455 length($html) + length($html_log_part) +
456 length($html_end) < MAX_MAIL_SIZE)
ce84a950
DJ
457 {
458 $html .= $html_log_part;
213e0eb2 459 $html .= $html_end;
ce84a950
DJ
460 $text .= $text_log_part;
461 } else {
462 my $msg = "Log output was too long to be sent by mail. ".
463 "See Task History for details!\n";
464 $text .= $msg;
465 $html .= "<p>$msg</p>";
466 $html .= $html_end;
467 }
468
7a0a8e67 469 my $subject = "vzdump backup status ($hostname) : $stat";
aaeeeebe 470
7a0a8e67
TL
471 my $dcconf = PVE::Cluster::cfs_read_file('datacenter.cfg');
472 my $mailfrom = $dcconf->{email_from} || "root";
aaeeeebe 473
7a0a8e67 474 PVE::Tools::sendmail($mailto, $subject, $text, $html, $mailfrom, "vzdump backup tool");
aaeeeebe
DM
475};
476
477sub new {
a7e42354 478 my ($class, $cmdline, $opts, $skiplist) = @_;
aaeeeebe
DM
479
480 mkpath $logdir;
481
482 check_bin ('cp');
483 check_bin ('df');
484 check_bin ('sendmail');
485 check_bin ('rsync');
486 check_bin ('tar');
487 check_bin ('mount');
488 check_bin ('umount');
489 check_bin ('cstream');
490 check_bin ('ionice');
491
47664cbe 492 if ($opts->{mode} && $opts->{mode} eq 'snapshot') {
aaeeeebe
DM
493 check_bin ('lvcreate');
494 check_bin ('lvs');
495 check_bin ('lvremove');
496 }
497
498 my $defaults = read_vzdump_defaults();
499
500 foreach my $k (keys %$defaults) {
acc963c3 501 next if $k eq 'exclude-path' || $k eq 'prune-backups'; # dealt with separately
aaeeeebe
DM
502 if ($k eq 'dumpdir' || $k eq 'storage') {
503 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
504 !defined ($opts->{storage});
505 } else {
506 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
507 }
508 }
509
aaeeeebe
DM
510 $opts->{dumpdir} =~ s|/+$|| if ($opts->{dumpdir});
511 $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
512
a7e42354 513 $skiplist = [] if !$skiplist;
94009776
TL
514 my $self = bless {
515 cmdline => $cmdline,
516 opts => $opts,
517 skiplist => $skiplist,
518 }, $class;
aaeeeebe 519
45f16a06 520 my $findexcl = $self->{findexcl} = [];
f4a8bab4 521 if ($defaults->{'exclude-path'}) {
45f16a06 522 push @$findexcl, @{$defaults->{'exclude-path'}};
f4a8bab4
DM
523 }
524
aaeeeebe 525 if ($opts->{'exclude-path'}) {
45f16a06 526 push @$findexcl, @{$opts->{'exclude-path'}};
aaeeeebe
DM
527 }
528
529 if ($opts->{stdexcludes}) {
1353489e
TL
530 push @$findexcl,
531 '/tmp/?*',
532 '/var/tmp/?*',
533 '/var/run/?*.pid',
534 ;
aaeeeebe
DM
535 }
536
537 foreach my $p (@plugins) {
1353489e 538 my $pd = $p->new($self);
aaeeeebe
DM
539
540 push @{$self->{plugins}}, $pd;
aaeeeebe
DM
541 }
542
1a87db9e 543 if (defined($opts->{storage}) && $opts->{stdout}) {
a6fcd7d9
FE
544 die "cannot use options 'storage' and 'stdout' at the same time\n";
545 } elsif (defined($opts->{storage}) && defined($opts->{dumpdir})) {
546 die "cannot use options 'storage' and 'dumpdir' at the same time\n";
1a87db9e
DM
547 }
548
aaeeeebe 549 if (!$opts->{dumpdir} && !$opts->{storage}) {
19d5c0f2 550 $opts->{storage} = 'local';
aaeeeebe
DM
551 }
552
3f488b61
FE
553 # Enforced by the API too, but these options might come in via defaults. Drop them if necessary.
554 if (!$opts->{storage}) {
555 delete $opts->{$_} for qw(notes-template protected);
556 }
557
403761c4 558 my $errors = '';
3c5a7616
FE
559 my $add_error = sub {
560 my ($error) = @_;
561 $errors .= "\n" if $errors;
562 chomp($error);
563 $errors .= $error;
564 };
403761c4 565
c527d28f
FE
566 eval {
567 $self->{job_init_log} = '';
568 open my $job_init_fd, '>', \$self->{job_init_log};
569 $self->run_hook_script('job-init', undef, $job_init_fd);
570 close $job_init_fd;
571
572 PVE::Cluster::cfs_update(); # Pick up possible changes made by the hook script.
573 };
574 $add_error->($@) if $@;
575
aaeeeebe 576 if ($opts->{storage}) {
164651da
FE
577 my $storage_cfg = PVE::Storage::config();
578 eval { PVE::Storage::activate_storage($storage_cfg, $opts->{storage}) };
3c5a7616 579 $add_error->("could not activate storage '$opts->{storage}': $@") if $@;
164651da 580
1e4583d5 581 my $info = eval { storage_info ($opts->{storage}) };
e6946086 582 if (my $err = $@) {
3c5a7616 583 $add_error->("could not get storage information for '$opts->{storage}': $err");
e6946086
FE
584 } else {
585 $opts->{dumpdir} = $info->{dumpdir};
586 $opts->{scfg} = $info->{scfg};
587 $opts->{pbs} = $info->{pbs};
acc963c3 588 $opts->{'prune-backups'} //= $info->{'prune-backups'};
e6946086 589 }
aaeeeebe 590 } elsif ($opts->{dumpdir}) {
3c5a7616 591 $add_error->("dumpdir '$opts->{dumpdir}' does not exist")
aaeeeebe
DM
592 if ! -d $opts->{dumpdir};
593 } else {
60e049c2 594 die "internal error";
aaeeeebe
DM
595 }
596
acc963c3 597 $opts->{'prune-backups'} //= $defaults->{'prune-backups'};
5b6b72e6 598
1db8529e
FE
599 # avoid triggering any remove code path if keep-all is set
600 $opts->{remove} = 0 if $opts->{'prune-backups'}->{'keep-all'};
601
aaeeeebe 602 if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
3c5a7616 603 $add_error->("tmpdir '$opts->{tmpdir}' does not exist");
403761c4
WB
604 }
605
606 if ($errors) {
607 eval { $self->sendmail([], 0, $errors); };
608 debugmsg ('err', $@) if $@;
609 die "$errors\n";
aaeeeebe
DM
610 }
611
612 return $self;
aaeeeebe
DM
613}
614
aaeeeebe
DM
615sub get_mount_info {
616 my ($dir) = @_;
617
8572d646
DM
618 # Note: df 'available' can be negative, and percentage set to '-'
619
d93d0459 620 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
aaeeeebe 621
d93d0459 622 my $res;
aaeeeebe 623
d93d0459
DM
624 my $parser = sub {
625 my $line = shift;
8572d646
DM
626 if (my ($fsid, $fstype, undef, $mp) = $line =~
627 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
d93d0459
DM
628 $res = {
629 device => $fsid,
630 fstype => $fstype,
631 mountpoint => $mp,
632 };
633 }
aaeeeebe 634 };
d93d0459
DM
635
636 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
637 warn $@ if $@;
638
639 return $res;
aaeeeebe
DM
640}
641
aaeeeebe 642sub getlock {
eab837c4 643 my ($self, $upid) = @_;
aaeeeebe 644
8682f6fc 645 my $fh;
60e049c2 646
aaeeeebe 647 my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
60e049c2 648
dc6e0a52 649 die "missing UPID" if !$upid; # should not happen
eab837c4 650
5620e576
TL
651 my $SERVER_FLCK;
652 if (!open ($SERVER_FLCK, '>>', "$lockfile")) {
aaeeeebe 653 debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
6ec9de44 654 die "can't open lock on file '$lockfile' - $!";
aaeeeebe
DM
655 }
656
5620e576 657 if (!flock ($SERVER_FLCK, LOCK_EX|LOCK_NB)) {
eab837c4 658 if (!$maxwait) {
76189130
TL
659 debugmsg ('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
660 die "can't acquire lock '$lockfile' (wait = 0)";
eab837c4 661 }
aaeeeebe 662
eab837c4 663 debugmsg('info', "trying to get global lock - waiting...", undef, 1);
eab837c4
DM
664 eval {
665 alarm ($maxwait * 60);
60e049c2 666
eab837c4 667 local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
aaeeeebe 668
5620e576 669 if (!flock ($SERVER_FLCK, LOCK_EX)) {
eab837c4 670 my $err = $!;
5620e576 671 close ($SERVER_FLCK);
eab837c4
DM
672 alarm (0);
673 die "$err\n";
674 }
aaeeeebe 675 alarm (0);
eab837c4 676 };
aaeeeebe 677 alarm (0);
60e049c2 678
eab837c4 679 my $err = $@;
60e049c2 680
eab837c4 681 if ($err) {
76189130
TL
682 debugmsg ('err', "can't acquire lock '$lockfile' - $err", undef, 1);
683 die "can't acquire lock '$lockfile' - $err";
eab837c4 684 }
aaeeeebe 685
eab837c4 686 debugmsg('info', "got global lock", undef, 1);
aaeeeebe
DM
687 }
688
eab837c4 689 PVE::Tools::file_set_contents($pidfile, $upid);
875c2e5a
FE
690
691 return $SERVER_FLCK;
aaeeeebe
DM
692}
693
694sub run_hook_script {
695 my ($self, $phase, $task, $logfd) = @_;
696
697 my $opts = $self->{opts};
698
699 my $script = $opts->{script};
aaeeeebe
DM
700 return if !$script;
701
0ac20586
TL
702 die "Error: The hook script '$script' does not exist.\n" if ! -f $script;
703 die "Error: The hook script '$script' is not executable.\n" if ! -x $script;
59798893 704
58f763e1 705 my $cmd = [$script, $phase];
aaeeeebe 706
58f763e1
FG
707 if ($task) {
708 push @$cmd, $task->{mode};
709 push @$cmd, $task->{vmid};
710 }
aaeeeebe
DM
711
712 local %ENV;
28272ca2
DM
713 # set immutable opts directly (so they are available in all phases)
714 $ENV{STOREID} = $opts->{storage} if $opts->{storage};
715 $ENV{DUMPDIR} = $opts->{dumpdir} if $opts->{dumpdir};
716
6cba1855 717 foreach my $ek (qw(vmtype hostname target logfile)) {
aaeeeebe
DM
718 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
719 }
720
721 run_command ($logfd, $cmd);
722}
723
d7550e09 724sub compressor_info {
778d5b6d
TL
725 my ($opts) = @_;
726 my $opt_compress = $opts->{compress};
d7550e09
DM
727
728 if (!$opt_compress || $opt_compress eq '0') {
729 return undef;
730 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
731 return ('lzop', 'lzo');
732 } elsif ($opt_compress eq 'gzip') {
778d5b6d 733 if ($opts->{pigz} > 0) {
8555b100
TL
734 my $pigz_threads = $opts->{pigz};
735 if ($pigz_threads == 1) {
736 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
737 $pigz_threads = int(($cpuinfo->{cpus} + 1)/2);
738 }
819e4ff5 739 return ("pigz -p ${pigz_threads} --rsyncable", 'gz');
778d5b6d 740 } else {
e953f92a 741 return ('gzip --rsyncable', 'gz');
778d5b6d 742 }
3e2c5105
AA
743 } elsif ($opt_compress eq 'zstd') {
744 my $zstd_threads = $opts->{zstd} // 1;
745 if ($zstd_threads == 0) {
746 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
747 $zstd_threads = int(($cpuinfo->{cpus} + 1)/2);
748 }
7420d7ff 749 return ("zstd --rsyncable --threads=${zstd_threads}", 'zst');
d7550e09
DM
750 } else {
751 die "internal error - unknown compression option '$opt_compress'";
752 }
753}
899b8373 754
725c0555 755sub get_backup_file_list {
0a9ca6ca 756 my ($dir, $bkname) = @_;
899b8373
DM
757
758 my $bklist = [];
759 foreach my $fn (<$dir/${bkname}-*>) {
de2d177e
FE
760 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
761 if ($archive_info->{is_std_name}) {
7bffbd22 762 my $path = "$dir/$archive_info->{filename}";
de2d177e 763 my $backup = {
7bffbd22 764 'path' => $path,
de2d177e
FE
765 'ctime' => $archive_info->{ctime},
766 };
725c0555
FG
767 $backup->{mark} = "protected"
768 if -e PVE::Storage::protection_file_path($path);
de2d177e 769 push @{$bklist}, $backup;
899b8373
DM
770 }
771 }
772
773 return $bklist;
774}
60e049c2 775
aaeeeebe
DM
776sub exec_backup_task {
777 my ($self, $task) = @_;
60e049c2 778
aaeeeebe
DM
779 my $opts = $self->{opts};
780
e6946086 781 my $cfg = PVE::Storage::config();
aaeeeebe
DM
782 my $vmid = $task->{vmid};
783 my $plugin = $task->{plugin};
1a87db9e
DM
784
785 $task->{backup_time} = time();
786
787 my $pbs_group_name;
788 my $pbs_snapshot_name;
789
aaeeeebe 790 my $vmstarttime = time ();
60e049c2 791
aaeeeebe
DM
792 my $logfd;
793
794 my $cleanup = {};
795
4e0947c8
TL
796 my $log_vm_online_again = sub {
797 return if !defined($task->{vmstoptime});
798 $task->{vmconttime} //= time();
799 my $delay = $task->{vmconttime} - $task->{vmstoptime};
310cde8b 800 $delay = '<1' if $delay < 1;
4e0947c8
TL
801 debugmsg ('info', "guest is online again after $delay seconds", $logfd);
802 };
aaeeeebe
DM
803
804 eval {
805 die "unable to find VM '$vmid'\n" if !$plugin;
806
d51f5a1e
FE
807 my $vmtype = $plugin->type();
808
809 if ($self->{opts}->{pbs}) {
810 if ($vmtype eq 'lxc') {
811 $pbs_group_name = "ct/$vmid";
812 } elsif ($vmtype eq 'qemu') {
813 $pbs_group_name = "vm/$vmid";
814 } else {
815 die "pbs backup not implemented for plugin type '$vmtype'\n";
816 }
817 my $btime = strftime("%FT%TZ", gmtime($task->{backup_time}));
818 $pbs_snapshot_name = "$pbs_group_name/$btime";
819 }
820
2de3ee58 821 # for now we deny backups of a running ha managed service in *stop* mode
83ec8f81 822 # as it interferes with the HA stack (started services should not stop).
2de3ee58 823 if ($opts->{mode} eq 'stop' &&
83ec8f81 824 PVE::HA::Config::vm_is_ha_managed($vmid, 'started'))
2de3ee58
TL
825 {
826 die "Cannot execute a backup with stop mode on a HA managed and".
827 " enabled Service. Use snapshot mode or disable the Service.\n";
828 }
829
aaeeeebe
DM
830 my $tmplog = "$logdir/$vmtype-$vmid.log";
831
aaeeeebe 832 my $bkname = "vzdump-$vmtype-$vmid";
1a87db9e 833 my $basename = $bkname . strftime("-%Y_%m_%d-%H_%M_%S", localtime($task->{backup_time}));
aaeeeebe 834
e6946086
FE
835 my $prune_options = $opts->{'prune-backups'};
836
837 my $backup_limit = 0;
b63baa39 838 if (!$prune_options->{'keep-all'}) {
1db8529e
FE
839 foreach my $keep (values %{$prune_options}) {
840 $backup_limit += $keep;
841 }
e6946086 842 }
899b8373 843
bbd4cdd8 844 if (($backup_limit && !$opts->{remove}) || $opts->{protected}) {
1a87db9e 845 my $count;
bbd4cdd8 846 my $protected_count;
7bffbd22 847 if (my $storeid = $opts->{storage}) {
bbd4cdd8
FE
848 my @backups = grep {
849 !$_->{subtype} || $_->{subtype} eq $vmtype
850 } PVE::Storage::volume_list($cfg, $storeid, $vmid, 'backup')->@*;
851
852 $count = grep { !$_->{protected} } @backups;
853 $protected_count = scalar(@backups) - $count;
1a87db9e 854 } else {
725c0555 855 $count = grep { !$_->{mark} || $_->{mark} ne "protected" } get_backup_file_list($opts->{dumpdir}, $bkname)->@*;
1a87db9e 856 }
7bffbd22 857
bbd4cdd8
FE
858 if ($opts->{protected}) {
859 my $max_protected = PVE::Storage::get_max_protected_backups(
860 $opts->{scfg},
861 $opts->{storage},
862 );
863 if ($max_protected > -1 && $protected_count >= $max_protected) {
864 die "The number of protected backups per guest is limited to $max_protected ".
865 "on storage '$opts->{storage}'\n";
866 }
867 } elsif ($count >= $backup_limit) {
868 die "There is a max backup limit of $backup_limit enforced by the target storage ".
869 "or the vzdump parameters. Either increase the limit or delete old backups.\n";
870 }
899b8373
DM
871 }
872
7ddcb3af 873 if (!$self->{opts}->{pbs}) {
1a87db9e
DM
874 $task->{logfile} = "$opts->{dumpdir}/$basename.log";
875 }
aaeeeebe 876
757fd3d5 877 my $ext = $vmtype eq 'qemu' ? '.vma' : '.tar';
778d5b6d 878 my ($comp, $comp_ext) = compressor_info($opts);
d7550e09
DM
879 if ($comp && $comp_ext) {
880 $ext .= ".${comp_ext}";
881 }
aaeeeebe 882
7ddcb3af 883 if ($self->{opts}->{pbs}) {
1a87db9e 884 die "unable to pipe backup to stdout\n" if $opts->{stdout};
b3c3304f 885 $task->{target} = $pbs_snapshot_name;
aaeeeebe 886 } else {
1a87db9e 887 if ($opts->{stdout}) {
6cba1855 888 $task->{target} = '-';
1a87db9e 889 } else {
6cba1855 890 $task->{target} = $task->{tmptar} = "$opts->{dumpdir}/$basename$ext";
1a87db9e
DM
891 $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
892 unlink $task->{tmptar};
893 }
aaeeeebe
DM
894 }
895
896 $task->{vmtype} = $vmtype;
897
dfb16115 898 my $pid = $$;
01fc3672 899 if ($opts->{tmpdir}) {
dfb16115 900 $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp${pid}_$vmid/";
01fc3672 901 } elsif ($self->{opts}->{pbs}) {
dfb16115 902 $task->{tmpdir} = "/var/tmp/vzdumptmp${pid}_$vmid";
aaeeeebe
DM
903 } else {
904 # dumpdir is posix? then use it as temporary dir
5dc86eb8 905 my $info = get_mount_info($opts->{dumpdir});
60e049c2 906 if ($vmtype eq 'qemu' ||
aaeeeebe
DM
907 grep ($_ eq $info->{fstype}, @posix_filesystems)) {
908 $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
909 } else {
dfb16115 910 $task->{tmpdir} = "/var/tmp/vzdumptmp${pid}_$vmid";
aaeeeebe
DM
911 debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
912 "using $task->{tmpdir} for temporary files", $logfd);
913 }
914 }
915
916 rmtree $task->{tmpdir};
917 mkdir $task->{tmpdir};
918 -d $task->{tmpdir} ||
919 die "unable to create temporary directory '$task->{tmpdir}'";
920
921 $logfd = IO::File->new (">$tmplog") ||
922 die "unable to create log file '$tmplog'";
923
924 $task->{dumpdir} = $opts->{dumpdir};
ff00abe6 925 $task->{storeid} = $opts->{storage};
1a87db9e 926 $task->{scfg} = $opts->{scfg};
aaeeeebe
DM
927 $task->{tmplog} = $tmplog;
928
1a87db9e 929 unlink $task->{logfile} if defined($task->{logfile});
aaeeeebe 930
29f26f6d
DJ
931 debugmsg ('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
932 debugmsg ('info', "Backup started at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
933
934 $plugin->set_logfd ($logfd);
935
936 # test is VM is running
937 my ($running, $status_text) = $plugin->vm_status ($vmid);
938
939 debugmsg ('info', "status = ${status_text}", $logfd);
940
941 # lock VM (prevent config changes)
942 $plugin->lock_vm ($vmid);
943
944 $cleanup->{unlock} = 1;
945
946 # prepare
947
6acb632a 948 my $mode = $running ? $task->{mode} : 'stop';
aaeeeebe
DM
949
950 if ($mode eq 'snapshot') {
951 my %saved_task = %$task;
952 eval { $plugin->prepare ($task, $vmid, $mode); };
953 if (my $err = $@) {
954 die $err if $err !~ m/^mode failure/;
955 debugmsg ('info', $err, $logfd);
956 debugmsg ('info', "trying 'suspend' mode instead", $logfd);
957 $mode = 'suspend'; # so prepare is called again below
60e049c2 958 %$task = %saved_task;
aaeeeebe
DM
959 }
960 }
961
6acb632a
WB
962 $cleanup->{prepared} = 1;
963
aaeeeebe
DM
964 $task->{mode} = $mode;
965
966 debugmsg ('info', "backup mode: $mode", $logfd);
ff119724 967 debugmsg ('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd) if $opts->{bwlimit};
aaeeeebe
DM
968 debugmsg ('info', "ionice priority: $opts->{ionice}", $logfd);
969
970 if ($mode eq 'stop') {
aaeeeebe
DM
971 $plugin->prepare ($task, $vmid, $mode);
972
973 $self->run_hook_script ('backup-start', $task, $logfd);
974
975 if ($running) {
4922b7a9 976 debugmsg ('info', "stopping virtual guest", $logfd);
4e0947c8 977 $task->{vmstoptime} = time();
aaeeeebe
DM
978 $self->run_hook_script ('pre-stop', $task, $logfd);
979 $plugin->stop_vm ($task, $vmid);
980 $cleanup->{restart} = 1;
981 }
60e049c2 982
aaeeeebe
DM
983
984 } elsif ($mode eq 'suspend') {
aaeeeebe
DM
985 $plugin->prepare ($task, $vmid, $mode);
986
987 $self->run_hook_script ('backup-start', $task, $logfd);
988
8187f6b0
DM
989 if ($vmtype eq 'lxc') {
990 # pre-suspend rsync
991 $plugin->copy_data_phase1($task, $vmid);
992 }
993
ef7d3fdd 994 debugmsg ('info', "suspending guest", $logfd);
4e0947c8 995 $task->{vmstoptime} = time ();
aaeeeebe
DM
996 $self->run_hook_script ('pre-stop', $task, $logfd);
997 $plugin->suspend_vm ($task, $vmid);
998 $cleanup->{resume} = 1;
999
8187f6b0
DM
1000 if ($vmtype eq 'lxc') {
1001 # post-suspend rsync
1002 $plugin->copy_data_phase2($task, $vmid);
1003
ef7d3fdd 1004 debugmsg ('info', "resuming guest", $logfd);
8187f6b0
DM
1005 $cleanup->{resume} = 0;
1006 $self->run_hook_script('pre-restart', $task, $logfd);
1007 $plugin->resume_vm($task, $vmid);
d5047243 1008 $self->run_hook_script('post-restart', $task, $logfd);
4e0947c8 1009 $log_vm_online_again->();
8187f6b0 1010 }
60e049c2 1011
aaeeeebe 1012 } elsif ($mode eq 'snapshot') {
c5be0f8c
DM
1013 $self->run_hook_script ('backup-start', $task, $logfd);
1014
aaeeeebe
DM
1015 my $snapshot_count = $task->{snapshot_count} || 0;
1016
1017 $self->run_hook_script ('pre-stop', $task, $logfd);
1018
1019 if ($snapshot_count > 1) {
1020 debugmsg ('info', "suspend vm to make snapshot", $logfd);
4e0947c8 1021 $task->{vmstoptime} = time ();
aaeeeebe
DM
1022 $plugin->suspend_vm ($task, $vmid);
1023 $cleanup->{resume} = 1;
1024 }
1025
1026 $plugin->snapshot ($task, $vmid);
1027
1028 $self->run_hook_script ('pre-restart', $task, $logfd);
1029
1030 if ($snapshot_count > 1) {
1031 debugmsg ('info', "resume vm", $logfd);
1032 $cleanup->{resume} = 0;
1033 $plugin->resume_vm ($task, $vmid);
4e0947c8 1034 $log_vm_online_again->();
aaeeeebe
DM
1035 }
1036
d5047243
FG
1037 $self->run_hook_script ('post-restart', $task, $logfd);
1038
aaeeeebe
DM
1039 } else {
1040 die "internal error - unknown mode '$mode'\n";
1041 }
1042
1043 # assemble archive image
1044 $plugin->assemble ($task, $vmid);
60e049c2
TM
1045
1046 # produce archive
aaeeeebe
DM
1047
1048 if ($opts->{stdout}) {
1049 debugmsg ('info', "sending archive to stdout", $logfd);
d7550e09 1050 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
1051 $self->run_hook_script ('backup-end', $task, $logfd);
1052 return;
1053 }
1054
b3c3304f
TL
1055 my $archive_txt = $self->{opts}->{pbs} ? 'Proxmox Backup Server' : 'vzdump';
1056 debugmsg('info', "creating $archive_txt archive '$task->{target}'", $logfd);
d7550e09 1057 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe 1058
7ddcb3af 1059 if ($self->{opts}->{pbs}) {
e21a31a7 1060 # size is added to task struct in guest vzdump plugins
1a87db9e 1061 } else {
6cba1855
TL
1062 rename ($task->{tmptar}, $task->{target}) ||
1063 die "unable to rename '$task->{tmptar}' to '$task->{target}'\n";
aaeeeebe 1064
1a87db9e 1065 # determine size
6cba1855 1066 $task->{size} = (-s $task->{target}) || 0;
1a87db9e
DM
1067 my $cs = format_size ($task->{size});
1068 debugmsg ('info', "archive file size: $cs", $logfd);
1069 }
aaeeeebe 1070
bbd4cdd8
FE
1071 # Mark as protected before pruning.
1072 if (my $storeid = $opts->{storage}) {
1073 my $volname = $opts->{pbs} ? $task->{target} : basename($task->{target});
1074 my $volid = "${storeid}:backup/${volname}";
1075
e01438a7
FE
1076 if ($opts->{'notes-template'} && $opts->{'notes-template'} ne '') {
1077 debugmsg('info', "adding notes to backup", $logfd);
31213d61
FE
1078 my $notes = eval { $generate_notes->($opts->{'notes-template'}, $task); };
1079 if (my $err = $@) {
1080 debugmsg('warn', "unable to add notes - $err", $logfd);
1081 } else {
1082 eval { PVE::Storage::update_volume_attribute($cfg, $volid, 'notes', $notes) };
1083 debugmsg('warn', "unable to add notes - $@", $logfd) if $@;
1084 }
e01438a7
FE
1085 }
1086
bbd4cdd8
FE
1087 if ($opts->{protected}) {
1088 debugmsg('info', "marking backup as protected", $logfd);
1089 eval { PVE::Storage::update_volume_attribute($cfg, $volid, 'protected', 1) };
1090 die "unable to set protected flag - $@\n" if $@;
1091 }
1092 }
1093
e6946086 1094 if ($opts->{remove}) {
ca155141
TL
1095 my $keepstr = join(', ', map { "$_=$prune_options->{$_}" } sort keys %$prune_options);
1096 debugmsg ('info', "prune older backups with retention: $keepstr", $logfd);
b4546c7e 1097 my $pruned = 0;
f354fe47 1098 if (!defined($opts->{storage})) {
725c0555 1099 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
2fc939a9 1100
f354fe47 1101 PVE::Storage::prune_mark_backup_group($bklist, $prune_options);
e6946086 1102
f354fe47
FE
1103 foreach my $prune_entry (@{$bklist}) {
1104 next if $prune_entry->{mark} ne 'remove';
b4546c7e 1105 $pruned++;
f354fe47
FE
1106 my $archive_path = $prune_entry->{path};
1107 debugmsg ('info', "delete old backup '$archive_path'", $logfd);
1108 PVE::Storage::archive_remove($archive_path);
1a87db9e 1109 }
f354fe47 1110 } else {
b4546c7e
TL
1111 my $pruned_list = PVE::Storage::prune_backups(
1112 $cfg,
1113 $opts->{storage},
1114 $prune_options,
1115 $vmid,
1116 $vmtype,
1117 0,
1118 sub { debugmsg($_[0], $_[1], $logfd) },
1119 );
1120 $pruned = scalar(grep { $_->{mark} eq 'remove' } $pruned_list->@*);
aaeeeebe 1121 }
b4546c7e
TL
1122 my $log_pruned_extra = $pruned > 0 ? " not covered by keep-retention policy" : "";
1123 debugmsg ('info', "pruned $pruned backup(s)${log_pruned_extra}", $logfd);
aaeeeebe
DM
1124 }
1125
1126 $self->run_hook_script ('backup-end', $task, $logfd);
1127 };
1128 my $err = $@;
1129
1130 if ($plugin) {
1131 # clean-up
1132
1133 if ($cleanup->{unlock}) {
1134 eval { $plugin->unlock_vm ($vmid); };
1135 warn $@ if $@;
1136 }
1137
6acb632a 1138 if ($cleanup->{prepared}) {
ca2605e7
DM
1139 # only call cleanup when necessary (when prepare was executed)
1140 eval { $plugin->cleanup ($task, $vmid) };
1141 warn $@ if $@;
1142 }
aaeeeebe
DM
1143
1144 eval { $plugin->set_logfd (undef); };
1145 warn $@ if $@;
1146
60e049c2
TM
1147 if ($cleanup->{resume} || $cleanup->{restart}) {
1148 eval {
aaeeeebe
DM
1149 $self->run_hook_script ('pre-restart', $task, $logfd);
1150 if ($cleanup->{resume}) {
1151 debugmsg ('info', "resume vm", $logfd);
1152 $plugin->resume_vm ($task, $vmid);
1153 } else {
757fd3d5
DM
1154 my $running = $plugin->vm_status($vmid);
1155 if (!$running) {
1156 debugmsg ('info', "restarting vm", $logfd);
1157 $plugin->start_vm ($task, $vmid);
1158 }
d5047243
FG
1159 }
1160 $self->run_hook_script ('post-restart', $task, $logfd);
aaeeeebe
DM
1161 };
1162 my $err = $@;
1163 if ($err) {
1164 warn $err;
1165 } else {
4e0947c8 1166 $log_vm_online_again->();
aaeeeebe
DM
1167 }
1168 }
1169 }
1170
1171 eval { unlink $task->{tmptar} if $task->{tmptar} && -f $task->{tmptar}; };
1172 warn $@ if $@;
1173
fe6643b6 1174 eval { rmtree $task->{tmpdir} if $task->{tmpdir} && -d $task->{tmpdir}; };
aaeeeebe
DM
1175 warn $@ if $@;
1176
1177 my $delay = $task->{backuptime} = time () - $vmstarttime;
1178
1179 if ($err) {
1180 $task->{state} = 'err';
1181 $task->{msg} = $err;
1182 debugmsg ('err', "Backup of VM $vmid failed - $err", $logfd, 1);
29f26f6d 1183 debugmsg ('info', "Failed at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
1184
1185 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1186
1187 } else {
1188 $task->{state} = 'ok';
1189 my $tstr = format_time ($delay);
1190 debugmsg ('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
29f26f6d 1191 debugmsg ('info', "Backup finished at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
1192 }
1193
1194 close ($logfd) if $logfd;
60e049c2 1195
1a87db9e 1196 if ($task->{tmplog}) {
7ddcb3af 1197 if ($self->{opts}->{pbs}) {
1a87db9e 1198 if ($task->{state} eq 'ok') {
e8d9e1ed
TL
1199 eval {
1200 PVE::Storage::PBSPlugin::run_raw_client_cmd(
1201 $opts->{scfg},
1202 $opts->{storage},
1203 'upload-log',
1204 [ $pbs_snapshot_name, $task->{tmplog} ],
1205 errmsg => "uploading backup task log failed",
f332a167 1206 outfunc => sub {},
e8d9e1ed
TL
1207 );
1208 };
1209 debugmsg('warn', "$@") if $@; # $@ contains already error prefix
1a87db9e
DM
1210 }
1211 } elsif ($task->{logfile}) {
1212 system {'cp'} 'cp', $task->{tmplog}, $task->{logfile};
1213 }
aaeeeebe
DM
1214 }
1215
1216 eval { $self->run_hook_script ('log-end', $task); };
1217
1218 die $err if $err && $err =~ m/^interrupted by signal$/;
1219}
1220
1221sub exec_backup {
d7550e09 1222 my ($self, $rpcenv, $authuser) = @_;
aaeeeebe
DM
1223
1224 my $opts = $self->{opts};
1225
1226 debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
f647d0fc
FE
1227
1228 if (scalar(@{$self->{skiplist}})) {
1229 my $skip_string = join(', ', sort { $a <=> $b } @{$self->{skiplist}});
1230 debugmsg ('info', "skip external VMs: $skip_string");
1231 }
60e049c2 1232
aaeeeebe 1233 my $tasklist = [];
df5875b4
AL
1234 my $vzdump_plugins = {};
1235 foreach my $plugin (@{$self->{plugins}}) {
1236 my $type = $plugin->type();
1237 next if exists $vzdump_plugins->{$type};
1238 $vzdump_plugins->{$type} = $plugin;
1239 }
aaeeeebe 1240
df5875b4 1241 my $vmlist = PVE::Cluster::get_vmlist();
4d73f0e2
FE
1242 my $vmids = [ sort { $a <=> $b } @{$opts->{vmids}} ];
1243 foreach my $vmid (@{$vmids}) {
7f874148
FE
1244 my $plugin;
1245 if (defined($vmlist->{ids}->{$vmid})) {
1246 my $guest_type = $vmlist->{ids}->{$vmid}->{type};
1247 $plugin = $vzdump_plugins->{$guest_type};
1248 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], $opts->{all});
1249 }
df5875b4 1250 push @$tasklist, {
f839f3d1 1251 mode => $opts->{mode},
df5875b4 1252 plugin => $plugin,
f839f3d1
TL
1253 state => 'todo',
1254 vmid => $vmid,
1255 };
aaeeeebe
DM
1256 }
1257
44b21574
WB
1258 # Use in-memory files for the outer hook logs to pass them to sendmail.
1259 my $job_start_log = '';
1260 my $job_end_log = '';
1261 open my $job_start_fd, '>', \$job_start_log;
1262 open my $job_end_fd, '>', \$job_end_log;
1263
aaeeeebe
DM
1264 my $starttime = time();
1265 my $errcount = 0;
1266 eval {
1267
44b21574 1268 $self->run_hook_script ('job-start', undef, $job_start_fd);
aaeeeebe
DM
1269
1270 foreach my $task (@$tasklist) {
1271 $self->exec_backup_task ($task);
1272 $errcount += 1 if $task->{state} ne 'ok';
1273 }
1274
44b21574 1275 $self->run_hook_script ('job-end', undef, $job_end_fd);
aaeeeebe
DM
1276 };
1277 my $err = $@;
1278
44b21574 1279 $self->run_hook_script ('job-abort', undef, $job_end_fd) if $err;
aaeeeebe
DM
1280
1281 if ($err) {
1282 debugmsg ('err', "Backup job failed - $err", undef, 1);
1283 } else {
1284 if ($errcount) {
1285 debugmsg ('info', "Backup job finished with errors", undef, 1);
1286 } else {
61ca4432 1287 debugmsg ('info', "Backup job finished successfully", undef, 1);
aaeeeebe
DM
1288 }
1289 }
1290
44b21574
WB
1291 close $job_start_fd;
1292 close $job_end_fd;
1293
aaeeeebe
DM
1294 my $totaltime = time() - $starttime;
1295
b241deb7
FE
1296 eval {
1297 $self->sendmail(
1298 $tasklist,
1299 $totaltime,
1300 undef,
1301 $self->{job_init_log} . $job_start_log,
1302 $job_end_log,
1303 );
1304 };
aaeeeebe 1305 debugmsg ('err', $@) if $@;
4a4051d8
DM
1306
1307 die $err if $err;
1308
60e049c2 1309 die "job errors\n" if $errcount;
8682f6fc
WL
1310
1311 unlink $pidfile;
aaeeeebe
DM
1312}
1313
ac27b58d 1314
47664cbe
DM
1315sub option_exists {
1316 my $key = shift;
1317 return defined($confdesc->{$key});
1318}
1319
f8ed6af8
FE
1320# NOTE it might make sense to merge this and verify_vzdump_parameters(), but one
1321# needs to adapt command_line() in guest-common's PVE/VZDump/Common.pm and detect
1322# a second parsing attempt, because verify_vzdump_parameters() is called twice
1323# during the update_job API call.
1324sub parse_mailto_exclude_path {
1325 my ($param) = @_;
1326
1327 # exclude-path list need to be 0 separated
1328 if (defined($param->{'exclude-path'})) {
1329 my @expaths = split(/\0/, $param->{'exclude-path'} || '');
1330 $param->{'exclude-path'} = [ @expaths ];
1331 }
1332
1333 if (defined($param->{mailto})) {
1334 my @mailto = PVE::Tools::split_list(extract_param($param, 'mailto'));
1335 $param->{mailto} = [ @mailto ];
1336 }
1337
1338 return;
1339}
1340
31aef761
DM
1341sub verify_vzdump_parameters {
1342 my ($param, $check_missing) = @_;
1343
1344 raise_param_exc({ all => "option conflicts with option 'vmid'"})
eab837c4 1345 if $param->{all} && $param->{vmid};
31aef761
DM
1346
1347 raise_param_exc({ exclude => "option conflicts with option 'vmid'"})
1348 if $param->{exclude} && $param->{vmid};
1349
f3376261
TM
1350 raise_param_exc({ pool => "option conflicts with option 'vmid'"})
1351 if $param->{pool} && $param->{vmid};
1352
e6946086
FE
1353 raise_param_exc({ 'prune-backups' => "option conflicts with option 'maxfiles'"})
1354 if defined($param->{'prune-backups'}) && defined($param->{maxfiles});
1355
1c56bcf3 1356 $parse_prune_backups_maxfiles->($param, 'CLI parameters');
e6946086 1357
facf65a6
FE
1358 if (my $template = $param->{'notes-template'}) {
1359 eval { $verify_notes_template->($template); };
1360 raise_param_exc({'notes-template' => $@}) if $@;
1361 }
010ff16e 1362
f3376261 1363 $param->{all} = 1 if (defined($param->{exclude}) && !$param->{pool});
31aef761
DM
1364
1365 return if !$check_missing;
1366
1367 raise_param_exc({ vmid => "property is missing"})
f3376261 1368 if !($param->{all} || $param->{stop} || $param->{pool}) && !$param->{vmid};
8682f6fc
WL
1369
1370}
1371
eab837c4 1372sub stop_running_backups {
8682f6fc
WL
1373 my($self) = @_;
1374
eab837c4
DM
1375 my $upid = PVE::Tools::file_read_firstline($pidfile);
1376 return if !$upid;
8682f6fc 1377
eab837c4 1378 my $task = PVE::Tools::upid_decode($upid);
8682f6fc 1379
60e049c2 1380 if (PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart}) &&
eab837c4
DM
1381 PVE::ProcFSTools::read_proc_starttime($task->{pid}) == $task->{pstart}) {
1382 kill(15, $task->{pid});
1383 # wait max 15 seconds to shut down (else, do nothing for now)
1384 my $i;
1385 for ($i = 15; $i > 0; $i--) {
1386 last if !PVE::ProcFSTools::check_process_running(($task->{pid}, $task->{pstart}));
1387 sleep (1);
1388 }
76189130 1389 die "stopping backup process $task->{pid} failed\n" if $i == 0;
8682f6fc 1390 }
31aef761
DM
1391}
1392
5c4da4c3
AL
1393sub get_included_guests {
1394 my ($job) = @_;
1395
5c4da4c3 1396 my $vmids = [];
df5875b4
AL
1397 my $vmids_per_node = {};
1398
1399 my $vmlist = PVE::Cluster::get_vmlist();
5c4da4c3 1400
5c4da4c3
AL
1401 if ($job->{pool}) {
1402 $vmids = PVE::API2Tools::get_resource_pool_guest_members($job->{pool});
df5875b4 1403 } elsif ($job->{vmid}) {
05447e04 1404 $vmids = [ split_list($job->{vmid}) ];
da7cb515 1405 } elsif ($job->{all}) {
df5875b4 1406 # all or exclude
05447e04
TL
1407 my $exclude = check_vmids(split_list($job->{exclude}));
1408 my $excludehash = { map { $_ => 1 } @$exclude };
df5875b4 1409
05447e04 1410 for my $id (keys %{$vmlist->{ids}}) {
df5875b4
AL
1411 next if $excludehash->{$id};
1412 push @$vmids, $id;
1413 }
da7cb515
AL
1414 } else {
1415 return $vmids_per_node;
5c4da4c3 1416 }
50ba40ec 1417 $vmids = check_vmids(@$vmids);
5c4da4c3 1418
50ba40ec 1419 for my $vmid (@$vmids) {
7f874148
FE
1420 if (defined($vmlist->{ids}->{$vmid})) {
1421 my $node = $vmlist->{ids}->{$vmid}->{node};
1422 next if (defined $job->{node} && $job->{node} ne $node);
50ba40ec 1423
7f874148
FE
1424 push @{$vmids_per_node->{$node}}, $vmid;
1425 } else {
1426 push @{$vmids_per_node->{''}}, $vmid;
1427 }
5c4da4c3
AL
1428 }
1429
df5875b4 1430 return $vmids_per_node;
5c4da4c3
AL
1431}
1432
aaeeeebe 14331;