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