]> git.proxmox.com Git - pve-manager.git/blame - PVE/VZDump.pm
ceph: config hash fallback style improvement
[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
374304db 321my sub read_backup_task_logs {
c4afde55 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
374304db 348my sub build_guest_table {
c4afde55
LW
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
374304db 402my sub sanitize_task_list {
c4afde55
LW
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
878d9af6 417my sub aggregate_task_statistics {
c4afde55 418 my ($tasklist) = @_;
8b4b4860 419
c4afde55 420 my $error_count = 0;
878d9af6 421 my $total_size = 0;
c4afde55
LW
422 for my $task (@$tasklist) {
423 $error_count++ if $task->{state} ne 'ok';
878d9af6 424 $total_size += $task->{size} if $task->{state} eq 'ok';
403761c4 425 }
aaeeeebe 426
878d9af6 427 return ($error_count, $total_size);
c4afde55
LW
428}
429
374304db 430my sub get_hostname {
4a4051d8 431 my $hostname = `hostname -f` || PVE::INotify::nodename();
aaeeeebe 432 chomp $hostname;
c4afde55
LW
433 return $hostname;
434}
aaeeeebe 435
c4afde55 436my $subject_template = "vzdump backup status ({{hostname}}): {{status-text}}";
7a0a8e67 437
c4afde55
LW
438my $body_template = <<EOT;
439{{error-message}}
440{{heading-1 "Details"}}
441{{table guest-table}}
878d9af6 442{{#verbatim}}
c4afde55 443Total running time: {{duration total-time}}
878d9af6
LW
444Total size: {{human-bytes total-size}}
445{{/verbatim}}
c4afde55
LW
446{{heading-1 "Logs"}}
447{{verbatim-monospaced logs}}
448EOT
aaeeeebe 449
c4afde55 450use constant MAX_LOG_SIZE => 1024*1024;
aaeeeebe 451
c4afde55
LW
452sub send_notification {
453 my ($self, $tasklist, $total_time, $err, $detail_pre, $detail_post) = @_;
aaeeeebe 454
c4afde55
LW
455 my $opts = $self->{opts};
456 my $mailto = $opts->{mailto};
457 my $cmdline = $self->{cmdline};
38035bdf
LW
458 my $policy = $opts->{mailnotification} // 'always';
459 my $mode = $opts->{"notification-mode"} // 'auto';
c4afde55
LW
460
461 sanitize_task_list($tasklist);
878d9af6 462 my ($error_count, $total_size) = aggregate_task_statistics($tasklist);
c4afde55
LW
463
464 my $failed = ($error_count || $err);
465
c4afde55
LW
466 my $status_text = $failed ? 'backup failed' : 'backup successful';
467
468 if ($err) {
469 if ($err =~ /\n/) {
470 $status_text .= ": multiple problems";
ce84a950 471 } else {
c4afde55
LW
472 $status_text .= ": $err";
473 $err = undef;
aaeeeebe 474 }
aaeeeebe 475 }
c4afde55
LW
476
477 my $text_log_part = "$cmdline\n\n";
478 $text_log_part .= $detail_pre . "\n" if defined($detail_pre);
479 $text_log_part .= read_backup_task_logs($tasklist);
480 $text_log_part .= $detail_post if defined($detail_post);
481
482 if (length($text_log_part) > MAX_LOG_SIZE)
ce84a950 483 {
c4afde55
LW
484 # Let's limit the maximum length of included logs
485 $text_log_part = "Log output was too long to be sent. ".
ce84a950 486 "See Task History for details!\n";
c4afde55
LW
487 };
488
e95a9a33
LW
489 my $hostname = get_hostname();
490
c4afde55 491 my $notification_props = {
878d9af6 492 "hostname" => $hostname,
c4afde55 493 "error-message" => $err,
878d9af6
LW
494 "guest-table" => build_guest_table($tasklist),
495 "logs" => $text_log_part,
496 "status-text" => $status_text,
497 "total-time" => $total_time,
498 "total-size" => $total_size,
c4afde55
LW
499 };
500
e95a9a33 501 my $fields = {
38035bdf
LW
502 # TODO: There is no straight-forward way yet to get the
503 # backup job id here... (I think pvescheduler would need
504 # to pass that to the vzdump call?)
e95a9a33
LW
505 type => "vzdump",
506 hostname => $hostname,
507 };
508
38035bdf
LW
509 my $severity = $failed ? "error" : "info";
510 my $email_configured = $mailto && scalar(@$mailto);
511
512 if (($mode eq 'auto' && $email_configured) || $mode eq 'legacy-sendmail') {
513 if ($email_configured && ($policy eq "always" || ($policy eq "failure" && $failed))) {
514 # Start out with an empty config. Might still contain
515 # built-ins, so we need to disable/remove them.
516 my $notification_config = Proxmox::RS::Notify->parse_config('', '');
517
518 # Remove built-in matchers, since we only want to send an
519 # email to the specified recipients and nobody else.
520 for my $matcher (@{$notification_config->get_matchers()}) {
521 $notification_config->delete_matcher($matcher->{name});
522 }
c4afde55 523
38035bdf
LW
524 # <, >, @ are not allowed in endpoint names, but that is only
525 # verified once the config is serialized. That means that
526 # we can rely on that fact that no other endpoint with this name exists.
527 my $endpoint_name = "<" . join(",", @$mailto) . ">";
528 $notification_config->add_sendmail_endpoint(
529 $endpoint_name,
530 $mailto,
531 undef,
532 undef,
533 "vzdump backup tool"
534 );
535
536 my $endpoints = [$endpoint_name];
537
538 # Add a matcher that matches all notifications, set our
539 # newly created target as a target.
540 $notification_config->add_matcher(
541 "<matcher-$endpoint_name>",
542 $endpoints,
543 );
544
545 PVE::Notify::notify(
546 $severity,
547 $subject_template,
548 $body_template,
549 $notification_props,
550 $fields,
551 $notification_config
552 );
553 }
554 } else {
555 # We use the 'new' system, or we are set to 'auto' and
556 # no email addresses were configured.
557 PVE::Notify::notify(
558 $severity,
559 $subject_template,
560 $body_template,
561 $notification_props,
562 $fields,
c4afde55 563 );
ce84a950 564 }
aaeeeebe
DM
565};
566
567sub new {
a7e42354 568 my ($class, $cmdline, $opts, $skiplist) = @_;
aaeeeebe
DM
569
570 mkpath $logdir;
571
572 check_bin ('cp');
573 check_bin ('df');
574 check_bin ('sendmail');
575 check_bin ('rsync');
576 check_bin ('tar');
577 check_bin ('mount');
578 check_bin ('umount');
579 check_bin ('cstream');
580 check_bin ('ionice');
581
47664cbe 582 if ($opts->{mode} && $opts->{mode} eq 'snapshot') {
aaeeeebe
DM
583 check_bin ('lvcreate');
584 check_bin ('lvs');
585 check_bin ('lvremove');
586 }
587
588 my $defaults = read_vzdump_defaults();
589
590 foreach my $k (keys %$defaults) {
acc963c3 591 next if $k eq 'exclude-path' || $k eq 'prune-backups'; # dealt with separately
aaeeeebe
DM
592 if ($k eq 'dumpdir' || $k eq 'storage') {
593 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
594 !defined ($opts->{storage});
595 } else {
596 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
597 }
598 }
599
aaeeeebe
DM
600 $opts->{dumpdir} =~ s|/+$|| if ($opts->{dumpdir});
601 $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
602
a7e42354 603 $skiplist = [] if !$skiplist;
94009776
TL
604 my $self = bless {
605 cmdline => $cmdline,
606 opts => $opts,
607 skiplist => $skiplist,
608 }, $class;
aaeeeebe 609
45f16a06 610 my $findexcl = $self->{findexcl} = [];
f4a8bab4 611 if ($defaults->{'exclude-path'}) {
45f16a06 612 push @$findexcl, @{$defaults->{'exclude-path'}};
f4a8bab4
DM
613 }
614
aaeeeebe 615 if ($opts->{'exclude-path'}) {
45f16a06 616 push @$findexcl, @{$opts->{'exclude-path'}};
aaeeeebe
DM
617 }
618
619 if ($opts->{stdexcludes}) {
1353489e
TL
620 push @$findexcl,
621 '/tmp/?*',
622 '/var/tmp/?*',
623 '/var/run/?*.pid',
624 ;
aaeeeebe
DM
625 }
626
627 foreach my $p (@plugins) {
1353489e 628 my $pd = $p->new($self);
aaeeeebe
DM
629
630 push @{$self->{plugins}}, $pd;
aaeeeebe
DM
631 }
632
1a87db9e 633 if (defined($opts->{storage}) && $opts->{stdout}) {
a6fcd7d9
FE
634 die "cannot use options 'storage' and 'stdout' at the same time\n";
635 } elsif (defined($opts->{storage}) && defined($opts->{dumpdir})) {
636 die "cannot use options 'storage' and 'dumpdir' at the same time\n";
1a87db9e
DM
637 }
638
43f83ad9
FE
639 if (my $storage = get_storage_param($opts)) {
640 $opts->{storage} = $storage;
aaeeeebe
DM
641 }
642
3f488b61
FE
643 # Enforced by the API too, but these options might come in via defaults. Drop them if necessary.
644 if (!$opts->{storage}) {
645 delete $opts->{$_} for qw(notes-template protected);
646 }
647
403761c4 648 my $errors = '';
3c5a7616
FE
649 my $add_error = sub {
650 my ($error) = @_;
651 $errors .= "\n" if $errors;
652 chomp($error);
653 $errors .= $error;
654 };
403761c4 655
c527d28f
FE
656 eval {
657 $self->{job_init_log} = '';
658 open my $job_init_fd, '>', \$self->{job_init_log};
659 $self->run_hook_script('job-init', undef, $job_init_fd);
660 close $job_init_fd;
661
662 PVE::Cluster::cfs_update(); # Pick up possible changes made by the hook script.
663 };
664 $add_error->($@) if $@;
665
aaeeeebe 666 if ($opts->{storage}) {
164651da
FE
667 my $storage_cfg = PVE::Storage::config();
668 eval { PVE::Storage::activate_storage($storage_cfg, $opts->{storage}) };
3c5a7616 669 $add_error->("could not activate storage '$opts->{storage}': $@") if $@;
164651da 670
1e4583d5 671 my $info = eval { storage_info ($opts->{storage}) };
e6946086 672 if (my $err = $@) {
3c5a7616 673 $add_error->("could not get storage information for '$opts->{storage}': $err");
e6946086
FE
674 } else {
675 $opts->{dumpdir} = $info->{dumpdir};
676 $opts->{scfg} = $info->{scfg};
677 $opts->{pbs} = $info->{pbs};
acc963c3 678 $opts->{'prune-backups'} //= $info->{'prune-backups'};
e6946086 679 }
aaeeeebe 680 } elsif ($opts->{dumpdir}) {
3c5a7616 681 $add_error->("dumpdir '$opts->{dumpdir}' does not exist")
aaeeeebe
DM
682 if ! -d $opts->{dumpdir};
683 } else {
60e049c2 684 die "internal error";
aaeeeebe
DM
685 }
686
acc963c3 687 $opts->{'prune-backups'} //= $defaults->{'prune-backups'};
5b6b72e6 688
1db8529e
FE
689 # avoid triggering any remove code path if keep-all is set
690 $opts->{remove} = 0 if $opts->{'prune-backups'}->{'keep-all'};
691
aaeeeebe 692 if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
3c5a7616 693 $add_error->("tmpdir '$opts->{tmpdir}' does not exist");
403761c4
WB
694 }
695
696 if ($errors) {
c4afde55 697 eval { $self->send_notification([], 0, $errors); };
403761c4
WB
698 debugmsg ('err', $@) if $@;
699 die "$errors\n";
aaeeeebe
DM
700 }
701
702 return $self;
aaeeeebe
DM
703}
704
aaeeeebe
DM
705sub get_mount_info {
706 my ($dir) = @_;
707
8572d646
DM
708 # Note: df 'available' can be negative, and percentage set to '-'
709
d93d0459 710 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
aaeeeebe 711
d93d0459 712 my $res;
aaeeeebe 713
d93d0459
DM
714 my $parser = sub {
715 my $line = shift;
8572d646
DM
716 if (my ($fsid, $fstype, undef, $mp) = $line =~
717 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
d93d0459
DM
718 $res = {
719 device => $fsid,
720 fstype => $fstype,
721 mountpoint => $mp,
722 };
723 }
aaeeeebe 724 };
d93d0459
DM
725
726 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
727 warn $@ if $@;
728
729 return $res;
aaeeeebe
DM
730}
731
aaeeeebe 732sub getlock {
eab837c4 733 my ($self, $upid) = @_;
aaeeeebe 734
8682f6fc 735 my $fh;
60e049c2 736
aaeeeebe 737 my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
60e049c2 738
dc6e0a52 739 die "missing UPID" if !$upid; # should not happen
eab837c4 740
5620e576
TL
741 my $SERVER_FLCK;
742 if (!open ($SERVER_FLCK, '>>', "$lockfile")) {
aaeeeebe 743 debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
6ec9de44 744 die "can't open lock on file '$lockfile' - $!";
aaeeeebe
DM
745 }
746
5620e576 747 if (!flock ($SERVER_FLCK, LOCK_EX|LOCK_NB)) {
eab837c4 748 if (!$maxwait) {
76189130
TL
749 debugmsg ('err', "can't acquire lock '$lockfile' (wait = 0)", undef, 1);
750 die "can't acquire lock '$lockfile' (wait = 0)";
eab837c4 751 }
aaeeeebe 752
eab837c4 753 debugmsg('info', "trying to get global lock - waiting...", undef, 1);
eab837c4
DM
754 eval {
755 alarm ($maxwait * 60);
60e049c2 756
eab837c4 757 local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
aaeeeebe 758
5620e576 759 if (!flock ($SERVER_FLCK, LOCK_EX)) {
eab837c4 760 my $err = $!;
5620e576 761 close ($SERVER_FLCK);
eab837c4
DM
762 alarm (0);
763 die "$err\n";
764 }
aaeeeebe 765 alarm (0);
eab837c4 766 };
aaeeeebe 767 alarm (0);
60e049c2 768
eab837c4 769 my $err = $@;
60e049c2 770
eab837c4 771 if ($err) {
76189130
TL
772 debugmsg ('err', "can't acquire lock '$lockfile' - $err", undef, 1);
773 die "can't acquire lock '$lockfile' - $err";
eab837c4 774 }
aaeeeebe 775
eab837c4 776 debugmsg('info', "got global lock", undef, 1);
aaeeeebe
DM
777 }
778
eab837c4 779 PVE::Tools::file_set_contents($pidfile, $upid);
875c2e5a
FE
780
781 return $SERVER_FLCK;
aaeeeebe
DM
782}
783
784sub run_hook_script {
785 my ($self, $phase, $task, $logfd) = @_;
786
787 my $opts = $self->{opts};
788
789 my $script = $opts->{script};
aaeeeebe
DM
790 return if !$script;
791
0ac20586
TL
792 die "Error: The hook script '$script' does not exist.\n" if ! -f $script;
793 die "Error: The hook script '$script' is not executable.\n" if ! -x $script;
59798893 794
58f763e1 795 my $cmd = [$script, $phase];
aaeeeebe 796
58f763e1
FG
797 if ($task) {
798 push @$cmd, $task->{mode};
799 push @$cmd, $task->{vmid};
800 }
aaeeeebe
DM
801
802 local %ENV;
28272ca2
DM
803 # set immutable opts directly (so they are available in all phases)
804 $ENV{STOREID} = $opts->{storage} if $opts->{storage};
805 $ENV{DUMPDIR} = $opts->{dumpdir} if $opts->{dumpdir};
806
6cba1855 807 foreach my $ek (qw(vmtype hostname target logfile)) {
aaeeeebe
DM
808 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
809 }
810
811 run_command ($logfd, $cmd);
812}
813
d7550e09 814sub compressor_info {
778d5b6d
TL
815 my ($opts) = @_;
816 my $opt_compress = $opts->{compress};
d7550e09
DM
817
818 if (!$opt_compress || $opt_compress eq '0') {
819 return undef;
820 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
821 return ('lzop', 'lzo');
822 } elsif ($opt_compress eq 'gzip') {
778d5b6d 823 if ($opts->{pigz} > 0) {
8555b100
TL
824 my $pigz_threads = $opts->{pigz};
825 if ($pigz_threads == 1) {
826 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
827 $pigz_threads = int(($cpuinfo->{cpus} + 1)/2);
828 }
819e4ff5 829 return ("pigz -p ${pigz_threads} --rsyncable", 'gz');
778d5b6d 830 } else {
e953f92a 831 return ('gzip --rsyncable', 'gz');
778d5b6d 832 }
3e2c5105
AA
833 } elsif ($opt_compress eq 'zstd') {
834 my $zstd_threads = $opts->{zstd} // 1;
835 if ($zstd_threads == 0) {
836 my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
837 $zstd_threads = int(($cpuinfo->{cpus} + 1)/2);
838 }
9a023d55 839 return ("zstd --threads=${zstd_threads}", 'zst');
d7550e09
DM
840 } else {
841 die "internal error - unknown compression option '$opt_compress'";
842 }
843}
899b8373 844
725c0555 845sub get_backup_file_list {
0a9ca6ca 846 my ($dir, $bkname) = @_;
899b8373
DM
847
848 my $bklist = [];
849 foreach my $fn (<$dir/${bkname}-*>) {
de2d177e
FE
850 my $archive_info = eval { PVE::Storage::archive_info($fn) } // {};
851 if ($archive_info->{is_std_name}) {
7bffbd22 852 my $path = "$dir/$archive_info->{filename}";
de2d177e 853 my $backup = {
7bffbd22 854 'path' => $path,
de2d177e
FE
855 'ctime' => $archive_info->{ctime},
856 };
725c0555
FG
857 $backup->{mark} = "protected"
858 if -e PVE::Storage::protection_file_path($path);
de2d177e 859 push @{$bklist}, $backup;
899b8373
DM
860 }
861 }
862
863 return $bklist;
864}
60e049c2 865
aaeeeebe
DM
866sub exec_backup_task {
867 my ($self, $task) = @_;
60e049c2 868
aaeeeebe
DM
869 my $opts = $self->{opts};
870
e6946086 871 my $cfg = PVE::Storage::config();
aaeeeebe
DM
872 my $vmid = $task->{vmid};
873 my $plugin = $task->{plugin};
1a87db9e
DM
874
875 $task->{backup_time} = time();
876
877 my $pbs_group_name;
878 my $pbs_snapshot_name;
879
aaeeeebe 880 my $vmstarttime = time ();
60e049c2 881
aaeeeebe
DM
882 my $logfd;
883
884 my $cleanup = {};
885
4e0947c8
TL
886 my $log_vm_online_again = sub {
887 return if !defined($task->{vmstoptime});
888 $task->{vmconttime} //= time();
889 my $delay = $task->{vmconttime} - $task->{vmstoptime};
310cde8b 890 $delay = '<1' if $delay < 1;
4e0947c8
TL
891 debugmsg ('info', "guest is online again after $delay seconds", $logfd);
892 };
aaeeeebe
DM
893
894 eval {
895 die "unable to find VM '$vmid'\n" if !$plugin;
896
d51f5a1e
FE
897 my $vmtype = $plugin->type();
898
899 if ($self->{opts}->{pbs}) {
900 if ($vmtype eq 'lxc') {
901 $pbs_group_name = "ct/$vmid";
902 } elsif ($vmtype eq 'qemu') {
903 $pbs_group_name = "vm/$vmid";
904 } else {
905 die "pbs backup not implemented for plugin type '$vmtype'\n";
906 }
907 my $btime = strftime("%FT%TZ", gmtime($task->{backup_time}));
908 $pbs_snapshot_name = "$pbs_group_name/$btime";
909 }
910
2de3ee58 911 # for now we deny backups of a running ha managed service in *stop* mode
83ec8f81 912 # as it interferes with the HA stack (started services should not stop).
2de3ee58 913 if ($opts->{mode} eq 'stop' &&
83ec8f81 914 PVE::HA::Config::vm_is_ha_managed($vmid, 'started'))
2de3ee58
TL
915 {
916 die "Cannot execute a backup with stop mode on a HA managed and".
917 " enabled Service. Use snapshot mode or disable the Service.\n";
918 }
919
aaeeeebe
DM
920 my $tmplog = "$logdir/$vmtype-$vmid.log";
921
aaeeeebe 922 my $bkname = "vzdump-$vmtype-$vmid";
1a87db9e 923 my $basename = $bkname . strftime("-%Y_%m_%d-%H_%M_%S", localtime($task->{backup_time}));
aaeeeebe 924
e6946086
FE
925 my $prune_options = $opts->{'prune-backups'};
926
927 my $backup_limit = 0;
b63baa39 928 if (!$prune_options->{'keep-all'}) {
1db8529e
FE
929 foreach my $keep (values %{$prune_options}) {
930 $backup_limit += $keep;
931 }
e6946086 932 }
899b8373 933
bbd4cdd8 934 if (($backup_limit && !$opts->{remove}) || $opts->{protected}) {
1a87db9e 935 my $count;
bbd4cdd8 936 my $protected_count;
7bffbd22 937 if (my $storeid = $opts->{storage}) {
bbd4cdd8
FE
938 my @backups = grep {
939 !$_->{subtype} || $_->{subtype} eq $vmtype
940 } PVE::Storage::volume_list($cfg, $storeid, $vmid, 'backup')->@*;
941
942 $count = grep { !$_->{protected} } @backups;
943 $protected_count = scalar(@backups) - $count;
1a87db9e 944 } else {
725c0555 945 $count = grep { !$_->{mark} || $_->{mark} ne "protected" } get_backup_file_list($opts->{dumpdir}, $bkname)->@*;
1a87db9e 946 }
7bffbd22 947
bbd4cdd8
FE
948 if ($opts->{protected}) {
949 my $max_protected = PVE::Storage::get_max_protected_backups(
950 $opts->{scfg},
951 $opts->{storage},
952 );
953 if ($max_protected > -1 && $protected_count >= $max_protected) {
954 die "The number of protected backups per guest is limited to $max_protected ".
955 "on storage '$opts->{storage}'\n";
956 }
957 } elsif ($count >= $backup_limit) {
958 die "There is a max backup limit of $backup_limit enforced by the target storage ".
959 "or the vzdump parameters. Either increase the limit or delete old backups.\n";
960 }
899b8373
DM
961 }
962
7ddcb3af 963 if (!$self->{opts}->{pbs}) {
1a87db9e
DM
964 $task->{logfile} = "$opts->{dumpdir}/$basename.log";
965 }
aaeeeebe 966
757fd3d5 967 my $ext = $vmtype eq 'qemu' ? '.vma' : '.tar';
778d5b6d 968 my ($comp, $comp_ext) = compressor_info($opts);
d7550e09
DM
969 if ($comp && $comp_ext) {
970 $ext .= ".${comp_ext}";
971 }
aaeeeebe 972
7ddcb3af 973 if ($self->{opts}->{pbs}) {
1a87db9e 974 die "unable to pipe backup to stdout\n" if $opts->{stdout};
b3c3304f 975 $task->{target} = $pbs_snapshot_name;
aaeeeebe 976 } else {
1a87db9e 977 if ($opts->{stdout}) {
6cba1855 978 $task->{target} = '-';
1a87db9e 979 } else {
6cba1855 980 $task->{target} = $task->{tmptar} = "$opts->{dumpdir}/$basename$ext";
1a87db9e
DM
981 $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
982 unlink $task->{tmptar};
983 }
aaeeeebe
DM
984 }
985
986 $task->{vmtype} = $vmtype;
987
dfb16115 988 my $pid = $$;
01fc3672 989 if ($opts->{tmpdir}) {
dfb16115 990 $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp${pid}_$vmid/";
01fc3672 991 } elsif ($self->{opts}->{pbs}) {
dfb16115 992 $task->{tmpdir} = "/var/tmp/vzdumptmp${pid}_$vmid";
aaeeeebe
DM
993 } else {
994 # dumpdir is posix? then use it as temporary dir
5dc86eb8 995 my $info = get_mount_info($opts->{dumpdir});
60e049c2 996 if ($vmtype eq 'qemu' ||
aaeeeebe
DM
997 grep ($_ eq $info->{fstype}, @posix_filesystems)) {
998 $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
999 } else {
dfb16115 1000 $task->{tmpdir} = "/var/tmp/vzdumptmp${pid}_$vmid";
aaeeeebe
DM
1001 debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
1002 "using $task->{tmpdir} for temporary files", $logfd);
1003 }
1004 }
1005
1006 rmtree $task->{tmpdir};
1007 mkdir $task->{tmpdir};
1008 -d $task->{tmpdir} ||
1009 die "unable to create temporary directory '$task->{tmpdir}'";
1010
1011 $logfd = IO::File->new (">$tmplog") ||
1012 die "unable to create log file '$tmplog'";
1013
1014 $task->{dumpdir} = $opts->{dumpdir};
ff00abe6 1015 $task->{storeid} = $opts->{storage};
1a87db9e 1016 $task->{scfg} = $opts->{scfg};
aaeeeebe
DM
1017 $task->{tmplog} = $tmplog;
1018
1a87db9e 1019 unlink $task->{logfile} if defined($task->{logfile});
aaeeeebe 1020
29f26f6d
DJ
1021 debugmsg ('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
1022 debugmsg ('info', "Backup started at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
1023
1024 $plugin->set_logfd ($logfd);
1025
1026 # test is VM is running
1027 my ($running, $status_text) = $plugin->vm_status ($vmid);
1028
1029 debugmsg ('info', "status = ${status_text}", $logfd);
1030
1031 # lock VM (prevent config changes)
1032 $plugin->lock_vm ($vmid);
1033
1034 $cleanup->{unlock} = 1;
1035
1036 # prepare
1037
6acb632a 1038 my $mode = $running ? $task->{mode} : 'stop';
aaeeeebe
DM
1039
1040 if ($mode eq 'snapshot') {
1041 my %saved_task = %$task;
1042 eval { $plugin->prepare ($task, $vmid, $mode); };
1043 if (my $err = $@) {
1044 die $err if $err !~ m/^mode failure/;
1045 debugmsg ('info', $err, $logfd);
1046 debugmsg ('info', "trying 'suspend' mode instead", $logfd);
1047 $mode = 'suspend'; # so prepare is called again below
60e049c2 1048 %$task = %saved_task;
aaeeeebe
DM
1049 }
1050 }
1051
6acb632a
WB
1052 $cleanup->{prepared} = 1;
1053
aaeeeebe
DM
1054 $task->{mode} = $mode;
1055
1056 debugmsg ('info', "backup mode: $mode", $logfd);
ff119724 1057 debugmsg ('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd) if $opts->{bwlimit};
aaeeeebe
DM
1058 debugmsg ('info', "ionice priority: $opts->{ionice}", $logfd);
1059
1060 if ($mode eq 'stop') {
aaeeeebe
DM
1061 $plugin->prepare ($task, $vmid, $mode);
1062
1063 $self->run_hook_script ('backup-start', $task, $logfd);
1064
1065 if ($running) {
4922b7a9 1066 debugmsg ('info', "stopping virtual guest", $logfd);
4e0947c8 1067 $task->{vmstoptime} = time();
aaeeeebe
DM
1068 $self->run_hook_script ('pre-stop', $task, $logfd);
1069 $plugin->stop_vm ($task, $vmid);
1070 $cleanup->{restart} = 1;
1071 }
60e049c2 1072
aaeeeebe
DM
1073
1074 } elsif ($mode eq 'suspend') {
aaeeeebe
DM
1075 $plugin->prepare ($task, $vmid, $mode);
1076
1077 $self->run_hook_script ('backup-start', $task, $logfd);
1078
8187f6b0
DM
1079 if ($vmtype eq 'lxc') {
1080 # pre-suspend rsync
1081 $plugin->copy_data_phase1($task, $vmid);
1082 }
1083
ef7d3fdd 1084 debugmsg ('info', "suspending guest", $logfd);
4e0947c8 1085 $task->{vmstoptime} = time ();
aaeeeebe
DM
1086 $self->run_hook_script ('pre-stop', $task, $logfd);
1087 $plugin->suspend_vm ($task, $vmid);
1088 $cleanup->{resume} = 1;
1089
8187f6b0
DM
1090 if ($vmtype eq 'lxc') {
1091 # post-suspend rsync
1092 $plugin->copy_data_phase2($task, $vmid);
1093
ef7d3fdd 1094 debugmsg ('info', "resuming guest", $logfd);
8187f6b0
DM
1095 $cleanup->{resume} = 0;
1096 $self->run_hook_script('pre-restart', $task, $logfd);
1097 $plugin->resume_vm($task, $vmid);
d5047243 1098 $self->run_hook_script('post-restart', $task, $logfd);
4e0947c8 1099 $log_vm_online_again->();
8187f6b0 1100 }
60e049c2 1101
aaeeeebe 1102 } elsif ($mode eq 'snapshot') {
c5be0f8c
DM
1103 $self->run_hook_script ('backup-start', $task, $logfd);
1104
aaeeeebe
DM
1105 my $snapshot_count = $task->{snapshot_count} || 0;
1106
1107 $self->run_hook_script ('pre-stop', $task, $logfd);
1108
1109 if ($snapshot_count > 1) {
1110 debugmsg ('info', "suspend vm to make snapshot", $logfd);
4e0947c8 1111 $task->{vmstoptime} = time ();
aaeeeebe
DM
1112 $plugin->suspend_vm ($task, $vmid);
1113 $cleanup->{resume} = 1;
1114 }
1115
1116 $plugin->snapshot ($task, $vmid);
1117
1118 $self->run_hook_script ('pre-restart', $task, $logfd);
1119
1120 if ($snapshot_count > 1) {
1121 debugmsg ('info', "resume vm", $logfd);
1122 $cleanup->{resume} = 0;
1123 $plugin->resume_vm ($task, $vmid);
4e0947c8 1124 $log_vm_online_again->();
aaeeeebe
DM
1125 }
1126
d5047243
FG
1127 $self->run_hook_script ('post-restart', $task, $logfd);
1128
aaeeeebe
DM
1129 } else {
1130 die "internal error - unknown mode '$mode'\n";
1131 }
1132
1133 # assemble archive image
1134 $plugin->assemble ($task, $vmid);
60e049c2
TM
1135
1136 # produce archive
aaeeeebe
DM
1137
1138 if ($opts->{stdout}) {
1139 debugmsg ('info', "sending archive to stdout", $logfd);
d7550e09 1140 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
1141 $self->run_hook_script ('backup-end', $task, $logfd);
1142 return;
1143 }
1144
b3c3304f
TL
1145 my $archive_txt = $self->{opts}->{pbs} ? 'Proxmox Backup Server' : 'vzdump';
1146 debugmsg('info', "creating $archive_txt archive '$task->{target}'", $logfd);
d7550e09 1147 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe 1148
7ddcb3af 1149 if ($self->{opts}->{pbs}) {
e21a31a7 1150 # size is added to task struct in guest vzdump plugins
1a87db9e 1151 } else {
6cba1855
TL
1152 rename ($task->{tmptar}, $task->{target}) ||
1153 die "unable to rename '$task->{tmptar}' to '$task->{target}'\n";
aaeeeebe 1154
1a87db9e 1155 # determine size
6cba1855 1156 $task->{size} = (-s $task->{target}) || 0;
1a87db9e
DM
1157 my $cs = format_size ($task->{size});
1158 debugmsg ('info', "archive file size: $cs", $logfd);
1159 }
aaeeeebe 1160
bbd4cdd8
FE
1161 # Mark as protected before pruning.
1162 if (my $storeid = $opts->{storage}) {
1163 my $volname = $opts->{pbs} ? $task->{target} : basename($task->{target});
1164 my $volid = "${storeid}:backup/${volname}";
1165
e01438a7
FE
1166 if ($opts->{'notes-template'} && $opts->{'notes-template'} ne '') {
1167 debugmsg('info', "adding notes to backup", $logfd);
31213d61
FE
1168 my $notes = eval { $generate_notes->($opts->{'notes-template'}, $task); };
1169 if (my $err = $@) {
1170 debugmsg('warn', "unable to add notes - $err", $logfd);
1171 } else {
1172 eval { PVE::Storage::update_volume_attribute($cfg, $volid, 'notes', $notes) };
1173 debugmsg('warn', "unable to add notes - $@", $logfd) if $@;
1174 }
e01438a7
FE
1175 }
1176
bbd4cdd8
FE
1177 if ($opts->{protected}) {
1178 debugmsg('info', "marking backup as protected", $logfd);
1179 eval { PVE::Storage::update_volume_attribute($cfg, $volid, 'protected', 1) };
1180 die "unable to set protected flag - $@\n" if $@;
1181 }
1182 }
1183
e6946086 1184 if ($opts->{remove}) {
ca155141
TL
1185 my $keepstr = join(', ', map { "$_=$prune_options->{$_}" } sort keys %$prune_options);
1186 debugmsg ('info', "prune older backups with retention: $keepstr", $logfd);
b4546c7e 1187 my $pruned = 0;
f354fe47 1188 if (!defined($opts->{storage})) {
725c0555 1189 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
2fc939a9 1190
f354fe47 1191 PVE::Storage::prune_mark_backup_group($bklist, $prune_options);
e6946086 1192
f354fe47
FE
1193 foreach my $prune_entry (@{$bklist}) {
1194 next if $prune_entry->{mark} ne 'remove';
b4546c7e 1195 $pruned++;
f354fe47
FE
1196 my $archive_path = $prune_entry->{path};
1197 debugmsg ('info', "delete old backup '$archive_path'", $logfd);
1198 PVE::Storage::archive_remove($archive_path);
1a87db9e 1199 }
f354fe47 1200 } else {
b4546c7e
TL
1201 my $pruned_list = PVE::Storage::prune_backups(
1202 $cfg,
1203 $opts->{storage},
1204 $prune_options,
1205 $vmid,
1206 $vmtype,
1207 0,
1208 sub { debugmsg($_[0], $_[1], $logfd) },
1209 );
1210 $pruned = scalar(grep { $_->{mark} eq 'remove' } $pruned_list->@*);
aaeeeebe 1211 }
b4546c7e
TL
1212 my $log_pruned_extra = $pruned > 0 ? " not covered by keep-retention policy" : "";
1213 debugmsg ('info', "pruned $pruned backup(s)${log_pruned_extra}", $logfd);
aaeeeebe
DM
1214 }
1215
1216 $self->run_hook_script ('backup-end', $task, $logfd);
1217 };
1218 my $err = $@;
1219
1220 if ($plugin) {
1221 # clean-up
1222
1223 if ($cleanup->{unlock}) {
1224 eval { $plugin->unlock_vm ($vmid); };
1225 warn $@ if $@;
1226 }
1227
6acb632a 1228 if ($cleanup->{prepared}) {
ca2605e7
DM
1229 # only call cleanup when necessary (when prepare was executed)
1230 eval { $plugin->cleanup ($task, $vmid) };
1231 warn $@ if $@;
1232 }
aaeeeebe
DM
1233
1234 eval { $plugin->set_logfd (undef); };
1235 warn $@ if $@;
1236
60e049c2
TM
1237 if ($cleanup->{resume} || $cleanup->{restart}) {
1238 eval {
aaeeeebe
DM
1239 $self->run_hook_script ('pre-restart', $task, $logfd);
1240 if ($cleanup->{resume}) {
1241 debugmsg ('info', "resume vm", $logfd);
1242 $plugin->resume_vm ($task, $vmid);
1243 } else {
757fd3d5
DM
1244 my $running = $plugin->vm_status($vmid);
1245 if (!$running) {
1246 debugmsg ('info', "restarting vm", $logfd);
1247 $plugin->start_vm ($task, $vmid);
1248 }
d5047243
FG
1249 }
1250 $self->run_hook_script ('post-restart', $task, $logfd);
aaeeeebe
DM
1251 };
1252 my $err = $@;
1253 if ($err) {
1254 warn $err;
1255 } else {
4e0947c8 1256 $log_vm_online_again->();
aaeeeebe
DM
1257 }
1258 }
1259 }
1260
1261 eval { unlink $task->{tmptar} if $task->{tmptar} && -f $task->{tmptar}; };
1262 warn $@ if $@;
1263
fe6643b6 1264 eval { rmtree $task->{tmpdir} if $task->{tmpdir} && -d $task->{tmpdir}; };
aaeeeebe
DM
1265 warn $@ if $@;
1266
1267 my $delay = $task->{backuptime} = time () - $vmstarttime;
1268
1269 if ($err) {
1270 $task->{state} = 'err';
1271 $task->{msg} = $err;
1272 debugmsg ('err', "Backup of VM $vmid failed - $err", $logfd, 1);
29f26f6d 1273 debugmsg ('info', "Failed at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
1274
1275 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
1276
1277 } else {
1278 $task->{state} = 'ok';
1279 my $tstr = format_time ($delay);
1280 debugmsg ('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
29f26f6d 1281 debugmsg ('info', "Backup finished at " . strftime("%F %H:%M:%S", localtime()));
aaeeeebe
DM
1282 }
1283
1284 close ($logfd) if $logfd;
60e049c2 1285
1a87db9e 1286 if ($task->{tmplog}) {
7ddcb3af 1287 if ($self->{opts}->{pbs}) {
1a87db9e 1288 if ($task->{state} eq 'ok') {
e8d9e1ed
TL
1289 eval {
1290 PVE::Storage::PBSPlugin::run_raw_client_cmd(
1291 $opts->{scfg},
1292 $opts->{storage},
1293 'upload-log',
1294 [ $pbs_snapshot_name, $task->{tmplog} ],
1295 errmsg => "uploading backup task log failed",
f332a167 1296 outfunc => sub {},
e8d9e1ed
TL
1297 );
1298 };
1299 debugmsg('warn', "$@") if $@; # $@ contains already error prefix
1a87db9e
DM
1300 }
1301 } elsif ($task->{logfile}) {
1302 system {'cp'} 'cp', $task->{tmplog}, $task->{logfile};
1303 }
aaeeeebe
DM
1304 }
1305
1306 eval { $self->run_hook_script ('log-end', $task); };
1307
1308 die $err if $err && $err =~ m/^interrupted by signal$/;
1309}
1310
1311sub exec_backup {
d7550e09 1312 my ($self, $rpcenv, $authuser) = @_;
aaeeeebe
DM
1313
1314 my $opts = $self->{opts};
1315
1316 debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
f647d0fc
FE
1317
1318 if (scalar(@{$self->{skiplist}})) {
1319 my $skip_string = join(', ', sort { $a <=> $b } @{$self->{skiplist}});
1320 debugmsg ('info', "skip external VMs: $skip_string");
1321 }
60e049c2 1322
aaeeeebe 1323 my $tasklist = [];
df5875b4
AL
1324 my $vzdump_plugins = {};
1325 foreach my $plugin (@{$self->{plugins}}) {
1326 my $type = $plugin->type();
1327 next if exists $vzdump_plugins->{$type};
1328 $vzdump_plugins->{$type} = $plugin;
1329 }
aaeeeebe 1330
df5875b4 1331 my $vmlist = PVE::Cluster::get_vmlist();
4d73f0e2
FE
1332 my $vmids = [ sort { $a <=> $b } @{$opts->{vmids}} ];
1333 foreach my $vmid (@{$vmids}) {
7f874148
FE
1334 my $plugin;
1335 if (defined($vmlist->{ids}->{$vmid})) {
1336 my $guest_type = $vmlist->{ids}->{$vmid}->{type};
1337 $plugin = $vzdump_plugins->{$guest_type};
1338 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], $opts->{all});
1339 }
df5875b4 1340 push @$tasklist, {
f839f3d1 1341 mode => $opts->{mode},
df5875b4 1342 plugin => $plugin,
f839f3d1
TL
1343 state => 'todo',
1344 vmid => $vmid,
1345 };
aaeeeebe
DM
1346 }
1347
44b21574
WB
1348 # Use in-memory files for the outer hook logs to pass them to sendmail.
1349 my $job_start_log = '';
1350 my $job_end_log = '';
1351 open my $job_start_fd, '>', \$job_start_log;
1352 open my $job_end_fd, '>', \$job_end_log;
1353
aaeeeebe
DM
1354 my $starttime = time();
1355 my $errcount = 0;
1356 eval {
1357
44b21574 1358 $self->run_hook_script ('job-start', undef, $job_start_fd);
aaeeeebe
DM
1359
1360 foreach my $task (@$tasklist) {
1361 $self->exec_backup_task ($task);
1362 $errcount += 1 if $task->{state} ne 'ok';
1363 }
1364
44b21574 1365 $self->run_hook_script ('job-end', undef, $job_end_fd);
aaeeeebe
DM
1366 };
1367 my $err = $@;
1368
aaeeeebe 1369 if ($err) {
573e8320
FE
1370 eval { $self->run_hook_script ('job-abort', undef, $job_end_fd); };
1371 $err .= $@ if $@;
aaeeeebe
DM
1372 debugmsg ('err', "Backup job failed - $err", undef, 1);
1373 } else {
1374 if ($errcount) {
1375 debugmsg ('info', "Backup job finished with errors", undef, 1);
1376 } else {
61ca4432 1377 debugmsg ('info', "Backup job finished successfully", undef, 1);
aaeeeebe
DM
1378 }
1379 }
1380
44b21574
WB
1381 close $job_start_fd;
1382 close $job_end_fd;
1383
aaeeeebe
DM
1384 my $totaltime = time() - $starttime;
1385
b241deb7 1386 eval {
c4afde55 1387 # otherwise $self->send_notification() will interpret it as multiple problems
268c6428
FE
1388 my $chomped_err = $err;
1389 chomp($chomped_err) if $chomped_err;
1390
c4afde55 1391 $self->send_notification(
b241deb7
FE
1392 $tasklist,
1393 $totaltime,
268c6428 1394 $chomped_err,
b241deb7
FE
1395 $self->{job_init_log} . $job_start_log,
1396 $job_end_log,
1397 );
1398 };
aaeeeebe 1399 debugmsg ('err', $@) if $@;
4a4051d8
DM
1400
1401 die $err if $err;
1402
60e049c2 1403 die "job errors\n" if $errcount;
8682f6fc
WL
1404
1405 unlink $pidfile;
aaeeeebe
DM
1406}
1407
ac27b58d 1408
47664cbe
DM
1409sub option_exists {
1410 my $key = shift;
1411 return defined($confdesc->{$key});
1412}
1413
f8ed6af8
FE
1414# NOTE it might make sense to merge this and verify_vzdump_parameters(), but one
1415# needs to adapt command_line() in guest-common's PVE/VZDump/Common.pm and detect
1416# a second parsing attempt, because verify_vzdump_parameters() is called twice
1417# during the update_job API call.
1418sub parse_mailto_exclude_path {
1419 my ($param) = @_;
1420
d6d3e55b 1421 # exclude-path list need to be 0 separated or be an array
f8ed6af8 1422 if (defined($param->{'exclude-path'})) {
d6d3e55b
DC
1423 my $expaths;
1424 if (ref($param->{'exclude-path'}) eq 'ARRAY') {
1425 $expaths = $param->{'exclude-path'};
1426 } else {
1427 $expaths = [split(/\0/, $param->{'exclude-path'} || '')];
1428 }
1429 $param->{'exclude-path'} = $expaths;
f8ed6af8
FE
1430 }
1431
1432 if (defined($param->{mailto})) {
1433 my @mailto = PVE::Tools::split_list(extract_param($param, 'mailto'));
1434 $param->{mailto} = [ @mailto ];
1435 }
1436
1437 return;
1438}
1439
31aef761
DM
1440sub verify_vzdump_parameters {
1441 my ($param, $check_missing) = @_;
1442
1443 raise_param_exc({ all => "option conflicts with option 'vmid'"})
eab837c4 1444 if $param->{all} && $param->{vmid};
31aef761
DM
1445
1446 raise_param_exc({ exclude => "option conflicts with option 'vmid'"})
1447 if $param->{exclude} && $param->{vmid};
1448
f3376261
TM
1449 raise_param_exc({ pool => "option conflicts with option 'vmid'"})
1450 if $param->{pool} && $param->{vmid};
1451
e6946086
FE
1452 raise_param_exc({ 'prune-backups' => "option conflicts with option 'maxfiles'"})
1453 if defined($param->{'prune-backups'}) && defined($param->{maxfiles});
1454
1c56bcf3 1455 $parse_prune_backups_maxfiles->($param, 'CLI parameters');
93880785 1456 parse_performance($param);
e6946086 1457
facf65a6
FE
1458 if (my $template = $param->{'notes-template'}) {
1459 eval { $verify_notes_template->($template); };
1460 raise_param_exc({'notes-template' => $@}) if $@;
1461 }
010ff16e 1462
f3376261 1463 $param->{all} = 1 if (defined($param->{exclude}) && !$param->{pool});
31aef761
DM
1464
1465 return if !$check_missing;
1466
1467 raise_param_exc({ vmid => "property is missing"})
f3376261 1468 if !($param->{all} || $param->{stop} || $param->{pool}) && !$param->{vmid};
8682f6fc
WL
1469
1470}
1471
eab837c4 1472sub stop_running_backups {
8682f6fc
WL
1473 my($self) = @_;
1474
eab837c4
DM
1475 my $upid = PVE::Tools::file_read_firstline($pidfile);
1476 return if !$upid;
8682f6fc 1477
eab837c4 1478 my $task = PVE::Tools::upid_decode($upid);
8682f6fc 1479
60e049c2 1480 if (PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart}) &&
eab837c4
DM
1481 PVE::ProcFSTools::read_proc_starttime($task->{pid}) == $task->{pstart}) {
1482 kill(15, $task->{pid});
1483 # wait max 15 seconds to shut down (else, do nothing for now)
1484 my $i;
1485 for ($i = 15; $i > 0; $i--) {
1486 last if !PVE::ProcFSTools::check_process_running(($task->{pid}, $task->{pstart}));
1487 sleep (1);
1488 }
76189130 1489 die "stopping backup process $task->{pid} failed\n" if $i == 0;
8682f6fc 1490 }
31aef761
DM
1491}
1492
5c4da4c3
AL
1493sub get_included_guests {
1494 my ($job) = @_;
1495
5c4da4c3 1496 my $vmids = [];
df5875b4
AL
1497 my $vmids_per_node = {};
1498
1499 my $vmlist = PVE::Cluster::get_vmlist();
5c4da4c3 1500
5c4da4c3
AL
1501 if ($job->{pool}) {
1502 $vmids = PVE::API2Tools::get_resource_pool_guest_members($job->{pool});
df5875b4 1503 } elsif ($job->{vmid}) {
05447e04 1504 $vmids = [ split_list($job->{vmid}) ];
da7cb515 1505 } elsif ($job->{all}) {
df5875b4 1506 # all or exclude
05447e04
TL
1507 my $exclude = check_vmids(split_list($job->{exclude}));
1508 my $excludehash = { map { $_ => 1 } @$exclude };
df5875b4 1509
05447e04 1510 for my $id (keys %{$vmlist->{ids}}) {
df5875b4
AL
1511 next if $excludehash->{$id};
1512 push @$vmids, $id;
1513 }
da7cb515
AL
1514 } else {
1515 return $vmids_per_node;
5c4da4c3 1516 }
50ba40ec 1517 $vmids = check_vmids(@$vmids);
5c4da4c3 1518
50ba40ec 1519 for my $vmid (@$vmids) {
7f874148
FE
1520 if (defined($vmlist->{ids}->{$vmid})) {
1521 my $node = $vmlist->{ids}->{$vmid}->{node};
1522 next if (defined $job->{node} && $job->{node} ne $node);
50ba40ec 1523
7f874148
FE
1524 push @{$vmids_per_node->{$node}}, $vmid;
1525 } else {
1526 push @{$vmids_per_node->{''}}, $vmid;
1527 }
5c4da4c3
AL
1528 }
1529
df5875b4 1530 return $vmids_per_node;
5c4da4c3
AL
1531}
1532
aaeeeebe 15331;