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