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