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