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