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