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