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