]> git.proxmox.com Git - pve-manager.git/blame - PVE/VZDump.pm
Pass what storage ID is being used to vzdump hook scripts
[pve-manager.git] / PVE / VZDump.pm
CommitLineData
aaeeeebe
DM
1package PVE::VZDump;
2
aaeeeebe
DM
3use strict;
4use warnings;
5use Fcntl ':flock';
31aef761 6use PVE::Exception qw(raise_param_exc);
4a4051d8 7use PVE::SafeSyslog;
aaeeeebe
DM
8use IO::File;
9use IO::Select;
10use IPC::Open3;
11use POSIX qw(strftime);
12use File::Path;
98e84b16 13use PVE::RPCEnvironment;
4a4051d8
DM
14use PVE::Storage;
15use PVE::Cluster qw(cfs_read_file);
aaeeeebe
DM
16use PVE::VZDump::OpenVZ;
17use Time::localtime;
18use Time::Local;
ac27b58d 19use PVE::JSONSchema qw(get_standard_option);
aaeeeebe
DM
20
21my @posix_filesystems = qw(ext3 ext4 nfs nfs4 reiserfs xfs);
22
23my $lockfile = '/var/run/vzdump.lock';
24
25my $logdir = '/var/log/vzdump';
26
27my @plugins = qw (PVE::VZDump::OpenVZ);
28
29# Load available plugins
30my $pveplug = "/usr/share/perl5/PVE/VZDump/QemuServer.pm";
31if (-f $pveplug) {
32 eval { require $pveplug; };
33 if (!$@) {
34 PVE::VZDump::QemuServer->import ();
35 push @plugins, "PVE::VZDump::QemuServer";
36 } else {
37 warn $@;
38 }
39}
40
41# helper functions
42
43my $debugstattxt = {
44 err => 'ERROR:',
45 info => 'INFO:',
46 warn => 'WARN:',
47};
48
49sub debugmsg {
50 my ($mtype, $msg, $logfd, $syslog) = @_;
51
52 chomp $msg;
53
54 return if !$msg;
55
56 my $pre = $debugstattxt->{$mtype} || $debugstattxt->{'err'};
57
58 my $timestr = strftime ("%b %d %H:%M:%S", CORE::localtime);
59
60 syslog ($mtype eq 'info' ? 'info' : 'err', "$pre $msg") if $syslog;
61
62 foreach my $line (split (/\n/, $msg)) {
63 print STDERR "$pre $line\n";
64 print $logfd "$timestr $pre $line\n" if $logfd;
65 }
66}
67
68sub run_command {
69 my ($logfd, $cmdstr, %param) = @_;
70
7f910306 71 my $logfunc = sub {
4a4051d8 72 my $line = shift;
4a4051d8 73 debugmsg ('info', $line, $logfd);
aaeeeebe
DM
74 };
75
7f910306 76 PVE::Tools::run_command($cmdstr, %param, logfunc => $logfunc);
aaeeeebe
DM
77}
78
79sub storage_info {
80 my $storage = shift;
81
4a4051d8
DM
82 my $cfg = cfs_read_file('storage.cfg');
83 my $scfg = PVE::Storage::storage_config($cfg, $storage);
aaeeeebe
DM
84 my $type = $scfg->{type};
85
86 die "can't use storage type '$type' for backup\n"
87 if (!($type eq 'dir' || $type eq 'nfs'));
88 die "can't use storage for backups - wrong content type\n"
89 if (!$scfg->{content}->{backup});
90
4a4051d8 91 PVE::Storage::activate_storage($cfg, $storage);
aaeeeebe
DM
92
93 return {
30edfad9 94 dumpdir => PVE::Storage::get_backup_dir($cfg, $storage),
19d5c0f2 95 maxfiles => $scfg->{maxfiles},
aaeeeebe
DM
96 };
97}
98
99sub format_size {
100 my $size = shift;
101
102 my $kb = $size / 1024;
103
104 if ($kb < 1024) {
105 return int ($kb) . "KB";
106 }
107
108 my $mb = $size / (1024*1024);
109
110 if ($mb < 1024) {
111 return int ($mb) . "MB";
112 } else {
113 my $gb = $mb / 1024;
114 return sprintf ("%.2fGB", $gb);
115 }
116}
117
118sub format_time {
119 my $seconds = shift;
120
121 my $hours = int ($seconds/3600);
122 $seconds = $seconds - $hours*3600;
123 my $min = int ($seconds/60);
124 $seconds = $seconds - $min*60;
125
126 return sprintf ("%02d:%02d:%02d", $hours, $min, $seconds);
127}
128
129sub encode8bit {
130 my ($str) = @_;
131
132 $str =~ s/^(.{990})/$1\n/mg; # reduce line length
133
134 return $str;
135}
136
137sub escape_html {
138 my ($str) = @_;
139
140 $str =~ s/&/&amp;/g;
141 $str =~ s/</&lt;/g;
142 $str =~ s/>/&gt;/g;
143
144 return $str;
145}
146
147sub check_bin {
148 my ($bin) = @_;
149
150 foreach my $p (split (/:/, $ENV{PATH})) {
151 my $fn = "$p/$bin";
152 if (-x $fn) {
153 return $fn;
154 }
155 }
156
157 die "unable to find command '$bin'\n";
158}
159
160sub check_vmids {
161 my (@vmids) = @_;
162
163 my $res = [];
164 foreach my $vmid (@vmids) {
165 die "ERROR: strange VM ID '${vmid}'\n" if $vmid !~ m/^\d+$/;
166 $vmid = int ($vmid); # remove leading zeros
4a4051d8 167 next if !$vmid;
aaeeeebe
DM
168 push @$res, $vmid;
169 }
170
171 return $res;
172}
173
174
175sub read_vzdump_defaults {
176
177 my $fn = "/etc/vzdump.conf";
178
179 my $res = {
180 bwlimit => 0,
181 ionice => 7,
182 size => 1024,
183 lockwait => 3*60, # 3 hours
184 stopwait => 10, # 10 minutes
185 mode => 'snapshot',
186 maxfiles => 1,
187 };
188
189 my $fh = IO::File->new ("<$fn");
190 return $res if !$fh;
191
192 my $line;
193 while (defined ($line = <$fh>)) {
194 next if $line =~ m/^\s*$/;
195 next if $line =~ m/^\#/;
196
197 if ($line =~ m/tmpdir:\s*(.*\S)\s*$/) {
198 $res->{tmpdir} = $1;
199 } elsif ($line =~ m/dumpdir:\s*(.*\S)\s*$/) {
200 $res->{dumpdir} = $1;
201 } elsif ($line =~ m/storage:\s*(\S+)\s*$/) {
202 $res->{storage} = $1;
203 } elsif ($line =~ m/script:\s*(.*\S)\s*$/) {
204 $res->{script} = $1;
205 } elsif ($line =~ m/bwlimit:\s*(\d+)\s*$/) {
206 $res->{bwlimit} = int($1);
207 } elsif ($line =~ m/ionice:\s*([0-8])\s*$/) {
208 $res->{ionice} = int($1);
209 } elsif ($line =~ m/lockwait:\s*(\d+)\s*$/) {
210 $res->{lockwait} = int($1);
211 } elsif ($line =~ m/stopwait:\s*(\d+)\s*$/) {
212 $res->{stopwait} = int($1);
213 } elsif ($line =~ m/size:\s*(\d+)\s*$/) {
214 $res->{size} = int($1);
215 } elsif ($line =~ m/maxfiles:\s*(\d+)\s*$/) {
216 $res->{maxfiles} = int($1);
f4a8bab4
DM
217 } elsif ($line =~ m/exclude-path:\s*(.*)\s*$/) {
218 $res->{'exclude-path'} = PVE::Tools::split_args($1);
aaeeeebe
DM
219 } elsif ($line =~ m/mode:\s*(stop|snapshot|suspend)\s*$/) {
220 $res->{mode} = $1;
221 } else {
222 debugmsg ('warn', "unable to parse configuration file '$fn' - error at line " . $., undef, 1);
223 }
224
225 }
226 close ($fh);
227
228 return $res;
229}
230
231
232sub find_add_exclude {
233 my ($self, $excltype, $value) = @_;
234
235 if (($excltype eq '-regex') || ($excltype eq '-files')) {
236 $value = "\.$value";
237 }
238
239 if ($excltype eq '-files') {
240 push @{$self->{findexcl}}, "'('", '-not', '-type', 'd', '-regex' , "'$value'", "')'", '-o';
241 } else {
242 push @{$self->{findexcl}}, "'('", $excltype , "'$value'", '-prune', "')'", '-o';
243 }
244}
245
aaeeeebe
DM
246my $sendmail = sub {
247 my ($self, $tasklist, $totaltime) = @_;
248
249 my $opts = $self->{opts};
250
251 my $mailto = $opts->{mailto};
252
4a4051d8 253 return if !($mailto && scalar(@$mailto));
aaeeeebe
DM
254
255 my $cmdline = $self->{cmdline};
256
257 my $ecount = 0;
258 foreach my $task (@$tasklist) {
259 $ecount++ if $task->{state} ne 'ok';
260 chomp $task->{msg} if $task->{msg};
261 $task->{backuptime} = 0 if !$task->{backuptime};
262 $task->{size} = 0 if !$task->{size};
263 $task->{tarfile} = 'unknown' if !$task->{tarfile};
264 $task->{hostname} = "VM $task->{vmid}" if !$task->{hostname};
265
266 if ($task->{state} eq 'todo') {
267 $task->{msg} = 'aborted';
268 }
269 }
270
271 my $stat = $ecount ? 'backup failed' : 'backup successful';
272
4a4051d8 273 my $hostname = `hostname -f` || PVE::INotify::nodename();
aaeeeebe
DM
274 chomp $hostname;
275
aaeeeebe
DM
276 my $boundary = "----_=_NextPart_001_".int(time).$$;
277
278 my $rcvrarg = '';
279 foreach my $r (@$mailto) {
280 $rcvrarg .= " '$r'";
281 }
282
283 open (MAIL,"|sendmail -B 8BITMIME $rcvrarg") ||
284 die "unable to open 'sendmail' - $!";
285
286 my $rcvrtxt = join (', ', @$mailto);
287
288 print MAIL "Content-Type: multipart/alternative;\n";
289 print MAIL "\tboundary=\"$boundary\"\n";
290 print MAIL "FROM: vzdump backup tool <root>\n";
291 print MAIL "TO: $rcvrtxt\n";
292 print MAIL "SUBJECT: vzdump backup status ($hostname) : $stat\n";
293 print MAIL "\n";
294 print MAIL "This is a multi-part message in MIME format.\n\n";
295 print MAIL "--$boundary\n";
296
297 print MAIL "Content-Type: text/plain;\n";
298 print MAIL "\tcharset=\"UTF8\"\n";
299 print MAIL "Content-Transfer-Encoding: 8bit\n";
300 print MAIL "\n";
301
302 # text part
303
304 my $fill = ' '; # Avoid The Remove Extra Line Breaks Issue (MS Outlook)
305
306 print MAIL sprintf ("${fill}%-10s %-6s %10s %10s %s\n", qw(VMID STATUS TIME SIZE FILENAME));
307 foreach my $task (@$tasklist) {
308 my $vmid = $task->{vmid};
309 if ($task->{state} eq 'ok') {
310
311 print MAIL sprintf ("${fill}%-10s %-6s %10s %10s %s\n", $vmid,
312 $task->{state},
313 format_time($task->{backuptime}),
314 format_size ($task->{size}),
315 $task->{tarfile});
316 } else {
317 print MAIL sprintf ("${fill}%-10s %-6s %10s %8.2fMB %s\n", $vmid,
318 $task->{state},
319 format_time($task->{backuptime}),
320 0, '-');
321 }
322 }
323 print MAIL "${fill}\n";
324 print MAIL "${fill}Detailed backup logs:\n";
325 print MAIL "${fill}\n";
326 print MAIL "$fill$cmdline\n";
327 print MAIL "${fill}\n";
328
329 foreach my $task (@$tasklist) {
330 my $vmid = $task->{vmid};
331 my $log = $task->{tmplog};
332 if (!$log) {
333 print MAIL "${fill}$vmid: no log available\n\n";
334 next;
335 }
336 open (TMP, "$log");
337 while (my $line = <TMP>) { print MAIL encode8bit ("${fill}$vmid: $line"); }
338 close (TMP);
339 print MAIL "${fill}\n";
340 }
341
342 # end text part
343 print MAIL "\n--$boundary\n";
344
345 print MAIL "Content-Type: text/html;\n";
346 print MAIL "\tcharset=\"UTF8\"\n";
347 print MAIL "Content-Transfer-Encoding: 8bit\n";
348 print MAIL "\n";
349
350 # html part
351
352 print MAIL "<html><body>\n";
353
354 print MAIL "<table border=1 cellpadding=3>\n";
355
356 print MAIL "<tr><td>VMID<td>NAME<td>STATUS<td>TIME<td>SIZE<td>FILENAME</tr>\n";
357
358 my $ssize = 0;
359
360 foreach my $task (@$tasklist) {
361 my $vmid = $task->{vmid};
362 my $name = $task->{hostname};
363
364 if ($task->{state} eq 'ok') {
365
366 $ssize += $task->{size};
367
368 print MAIL sprintf ("<tr><td>%s<td>%s<td>OK<td>%s<td align=right>%s<td>%s</tr>\n",
369 $vmid, $name,
370 format_time($task->{backuptime}),
371 format_size ($task->{size}),
372 escape_html ($task->{tarfile}));
373 } else {
374 print MAIL sprintf ("<tr><td>%s<td>%s<td><font color=red>FAILED<td>%s<td colspan=2>%s</tr>\n",
375
376 $vmid, $name, format_time($task->{backuptime}),
377 escape_html ($task->{msg}));
378 }
379 }
380
381 print MAIL sprintf ("<tr><td align=left colspan=3>TOTAL<td>%s<td>%s<td></tr>",
382 format_time ($totaltime), format_size ($ssize));
383
384 print MAIL "</table><br><br>\n";
385 print MAIL "Detailed backup logs:<br>\n";
386 print MAIL "<br>\n";
387 print MAIL "<pre>\n";
388 print MAIL escape_html($cmdline) . "\n";
389 print MAIL "\n";
390
391 foreach my $task (@$tasklist) {
392 my $vmid = $task->{vmid};
393 my $log = $task->{tmplog};
394 if (!$log) {
395 print MAIL "$vmid: no log available\n\n";
396 next;
397 }
398 open (TMP, "$log");
399 while (my $line = <TMP>) {
400 if ($line =~ m/^\S+\s\d+\s+\d+:\d+:\d+\s+(ERROR|WARN):/) {
401 print MAIL encode8bit ("$vmid: <font color=red>".
402 escape_html ($line) . "</font>");
403 } else {
404 print MAIL encode8bit ("$vmid: " . escape_html ($line));
405 }
406 }
407 close (TMP);
408 print MAIL "\n";
409 }
410 print MAIL "</pre>\n";
411
412 print MAIL "</body></html>\n";
413
414 # end html part
415 print MAIL "\n--$boundary--\n";
416
4a4051d8 417 close(MAIL);
aaeeeebe
DM
418};
419
420sub new {
a7e42354 421 my ($class, $cmdline, $opts, $skiplist) = @_;
aaeeeebe
DM
422
423 mkpath $logdir;
424
425 check_bin ('cp');
426 check_bin ('df');
427 check_bin ('sendmail');
428 check_bin ('rsync');
429 check_bin ('tar');
430 check_bin ('mount');
431 check_bin ('umount');
432 check_bin ('cstream');
433 check_bin ('ionice');
434
47664cbe 435 if ($opts->{mode} && $opts->{mode} eq 'snapshot') {
aaeeeebe
DM
436 check_bin ('lvcreate');
437 check_bin ('lvs');
438 check_bin ('lvremove');
439 }
440
441 my $defaults = read_vzdump_defaults();
442
84ad4385
DM
443 my $maxfiles = $opts->{maxfiles}; # save here, because we overwrite with default
444
899b8373
DM
445 $opts->{remove} = 1 if !defined($opts->{remove});
446
aaeeeebe
DM
447 foreach my $k (keys %$defaults) {
448 if ($k eq 'dumpdir' || $k eq 'storage') {
449 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
450 !defined ($opts->{storage});
451 } else {
452 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
453 }
454 }
455
aaeeeebe
DM
456 $opts->{dumpdir} =~ s|/+$|| if ($opts->{dumpdir});
457 $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
458
a7e42354
DM
459 $skiplist = [] if !$skiplist;
460 my $self = bless { cmdline => $cmdline, opts => $opts, skiplist => $skiplist };
aaeeeebe
DM
461
462 #always skip '.'
463 push @{$self->{findexcl}}, "'('", '-regex' , "'^\\.\$'", "')'", '-o';
464
465 $self->find_add_exclude ('-type', 's'); # skip sockets
466
f4a8bab4
DM
467 if ($defaults->{'exclude-path'}) {
468 foreach my $path (@{$defaults->{'exclude-path'}}) {
469 $self->find_add_exclude ('-regex', $path);
470 }
471 }
472
aaeeeebe
DM
473 if ($opts->{'exclude-path'}) {
474 foreach my $path (@{$opts->{'exclude-path'}}) {
475 $self->find_add_exclude ('-regex', $path);
476 }
477 }
478
479 if ($opts->{stdexcludes}) {
480 $self->find_add_exclude ('-files', '/var/log/.+');
481 $self->find_add_exclude ('-regex', '/tmp/.+');
482 $self->find_add_exclude ('-regex', '/var/tmp/.+');
483 $self->find_add_exclude ('-regex', '/var/run/.+pid');
484 }
485
486 foreach my $p (@plugins) {
487
488 my $pd = $p->new ($self);
489
490 push @{$self->{plugins}}, $pd;
aaeeeebe
DM
491 }
492
493 if (!$opts->{dumpdir} && !$opts->{storage}) {
19d5c0f2 494 $opts->{storage} = 'local';
aaeeeebe
DM
495 }
496
497 if ($opts->{storage}) {
498 my $info = storage_info ($opts->{storage});
499 $opts->{dumpdir} = $info->{dumpdir};
84ad4385 500 $maxfiles = $info->{maxfiles} if !defined($maxfiles) && defined($info->{maxfiles});
aaeeeebe
DM
501 } elsif ($opts->{dumpdir}) {
502 die "dumpdir '$opts->{dumpdir}' does not exist\n"
503 if ! -d $opts->{dumpdir};
504 } else {
505 die "internal error";
506 }
507
508 if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
509 die "tmpdir '$opts->{tmpdir}' does not exist\n";
510 }
511
84ad4385 512 $opts->{maxfiles} = $maxfiles if defined($maxfiles);
899b8373 513
aaeeeebe
DM
514 return $self;
515
516}
517
518sub get_lvm_mapping {
519
520 my $devmapper;
521
d93d0459
DM
522 my $cmd = ['lvs', '--units', 'm', '--separator', ':', '--noheadings',
523 '-o', 'vg_name,lv_name,lv_size' ];
524
525 my $parser = sub {
526 my $line = shift;
527 if ($line =~ m|^\s*(\S+):(\S+):(\d+(\.\d+))[Mm]$|) {
528 my $vg = $1;
529 my $lv = $2;
530 $devmapper->{"/dev/$vg/$lv"} = [$vg, $lv];
531 my $qlv = $lv;
532 $qlv =~ s/-/--/g;
533 my $qvg = $vg;
534 $qvg =~ s/-/--/g;
535 $devmapper->{"/dev/mapper/$qvg-$qlv"} = [$vg, $lv];
536 }
537 };
538
539 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
540 warn $@ if $@;
aaeeeebe
DM
541
542 return $devmapper;
543}
544
545sub get_mount_info {
546 my ($dir) = @_;
547
8572d646
DM
548 # Note: df 'available' can be negative, and percentage set to '-'
549
d93d0459 550 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
aaeeeebe 551
d93d0459 552 my $res;
aaeeeebe 553
d93d0459
DM
554 my $parser = sub {
555 my $line = shift;
8572d646
DM
556 if (my ($fsid, $fstype, undef, $mp) = $line =~
557 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
d93d0459
DM
558 $res = {
559 device => $fsid,
560 fstype => $fstype,
561 mountpoint => $mp,
562 };
563 }
aaeeeebe 564 };
d93d0459
DM
565
566 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
567 warn $@ if $@;
568
569 return $res;
aaeeeebe
DM
570}
571
572sub get_lvm_device {
573 my ($dir, $mapping) = @_;
574
5dc86eb8 575 my $info = get_mount_info($dir);
aaeeeebe
DM
576
577 return undef if !$info;
578
579 my $dev = $info->{device};
580
581 my ($vg, $lv);
582
583 ($vg, $lv) = @{$mapping->{$dev}} if defined $mapping->{$dev};
584
585 return wantarray ? ($dev, $info->{mountpoint}, $vg, $lv, $info->{fstype}) : $dev;
586}
587
588sub getlock {
589 my ($self) = @_;
590
591 my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
592
593 if (!open (SERVER_FLCK, ">>$lockfile")) {
594 debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
595 exit (-1);
596 }
597
598 if (flock (SERVER_FLCK, LOCK_EX|LOCK_NB)) {
599 return;
600 }
601
602 if (!$maxwait) {
603 debugmsg ('err', "can't aquire lock '$lockfile' (wait = 0)", undef, 1);
604 exit (-1);
605 }
606
607 debugmsg('info', "trying to get global lock - waiting...", undef, 1);
608
609 eval {
610 alarm ($maxwait * 60);
611
612 local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
613
614 if (!flock (SERVER_FLCK, LOCK_EX)) {
615 my $err = $!;
616 close (SERVER_FLCK);
617 alarm (0);
618 die "$err\n";
619 }
620 alarm (0);
621 };
622 alarm (0);
623
624 my $err = $@;
625
626 if ($err) {
627 debugmsg ('err', "can't aquire lock '$lockfile' - $err", undef, 1);
628 exit (-1);
629 }
630
631 debugmsg('info', "got global lock", undef, 1);
632}
633
634sub run_hook_script {
635 my ($self, $phase, $task, $logfd) = @_;
636
637 my $opts = $self->{opts};
638
639 my $script = $opts->{script};
640
641 return if !$script;
642
643 my $cmd = "$script $phase";
644
645 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
646
647 local %ENV;
648
ff00abe6 649 foreach my $ek (qw(vmtype dumpdir hostname tarfile logfile storeid)) {
aaeeeebe
DM
650 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
651 }
652
653 run_command ($logfd, $cmd);
654}
655
d7550e09
DM
656sub compressor_info {
657 my ($opt_compress) = @_;
658
659 if (!$opt_compress || $opt_compress eq '0') {
660 return undef;
661 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
662 return ('lzop', 'lzo');
663 } elsif ($opt_compress eq 'gzip') {
664 return ('gzip', 'gz');
665 } else {
666 die "internal error - unknown compression option '$opt_compress'";
667 }
668}
899b8373
DM
669
670sub get_backup_file_list {
671 my ($dir, $bkname, $exclude_fn) = @_;
672
673 my $bklist = [];
674 foreach my $fn (<$dir/${bkname}-*>) {
675 next if $exclude_fn && $fn eq $exclude_fn;
757fd3d5 676 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|((tar|vma)(\.(gz|lzo))?)))$!) {
899b8373
DM
677 $fn = "$dir/$1"; # untaint
678 my $t = timelocal ($7, $6, $5, $4, $3 - 1, $2 - 1900);
679 push @$bklist, [$fn, $t];
680 }
681 }
682
683 return $bklist;
684}
d7550e09 685
aaeeeebe
DM
686sub exec_backup_task {
687 my ($self, $task) = @_;
688
689 my $opts = $self->{opts};
690
691 my $vmid = $task->{vmid};
692 my $plugin = $task->{plugin};
693
694 my $vmstarttime = time ();
695
696 my $logfd;
697
698 my $cleanup = {};
699
700 my $vmstoptime = 0;
701
702 eval {
703 die "unable to find VM '$vmid'\n" if !$plugin;
704
705 my $vmtype = $plugin->type();
706
707 my $tmplog = "$logdir/$vmtype-$vmid.log";
708
709 my $lt = localtime();
710
711 my $bkname = "vzdump-$vmtype-$vmid";
712 my $basename = sprintf "${bkname}-%04d_%02d_%02d-%02d_%02d_%02d",
713 $lt->year + 1900, $lt->mon + 1, $lt->mday,
714 $lt->hour, $lt->min, $lt->sec;
715
899b8373
DM
716 my $maxfiles = $opts->{maxfiles};
717
718 if ($maxfiles && !$opts->{remove}) {
719 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
720 die "only $maxfiles backup(s) allowed - please consider to remove old backup files.\n"
721 if scalar(@$bklist) >= $maxfiles;
722 }
723
aaeeeebe
DM
724 my $logfile = $task->{logfile} = "$opts->{dumpdir}/$basename.log";
725
757fd3d5 726 my $ext = $vmtype eq 'qemu' ? '.vma' : '.tar';
d7550e09
DM
727 my ($comp, $comp_ext) = compressor_info($opts->{compress});
728 if ($comp && $comp_ext) {
729 $ext .= ".${comp_ext}";
730 }
aaeeeebe
DM
731
732 if ($opts->{stdout}) {
733 $task->{tarfile} = '-';
734 } else {
735 my $tarfile = $task->{tarfile} = "$opts->{dumpdir}/$basename$ext";
736 $task->{tmptar} = $task->{tarfile};
737 $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
738 unlink $task->{tmptar};
739 }
740
741 $task->{vmtype} = $vmtype;
742
743 if ($opts->{tmpdir}) {
744 $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp$$";
745 } else {
746 # dumpdir is posix? then use it as temporary dir
5dc86eb8 747 my $info = get_mount_info($opts->{dumpdir});
aaeeeebe
DM
748 if ($vmtype eq 'qemu' ||
749 grep ($_ eq $info->{fstype}, @posix_filesystems)) {
750 $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
751 } else {
752 $task->{tmpdir} = "/var/tmp/vzdumptmp$$";
753 debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
754 "using $task->{tmpdir} for temporary files", $logfd);
755 }
756 }
757
758 rmtree $task->{tmpdir};
759 mkdir $task->{tmpdir};
760 -d $task->{tmpdir} ||
761 die "unable to create temporary directory '$task->{tmpdir}'";
762
763 $logfd = IO::File->new (">$tmplog") ||
764 die "unable to create log file '$tmplog'";
765
766 $task->{dumpdir} = $opts->{dumpdir};
ff00abe6 767 $task->{storeid} = $opts->{storage};
aaeeeebe
DM
768 $task->{tmplog} = $tmplog;
769
770 unlink $logfile;
771
772 debugmsg ('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
773
774 $plugin->set_logfd ($logfd);
775
776 # test is VM is running
777 my ($running, $status_text) = $plugin->vm_status ($vmid);
778
779 debugmsg ('info', "status = ${status_text}", $logfd);
780
781 # lock VM (prevent config changes)
782 $plugin->lock_vm ($vmid);
783
784 $cleanup->{unlock} = 1;
785
786 # prepare
787
788 my $mode = $running ? $opts->{mode} : 'stop';
789
790 if ($mode eq 'snapshot') {
791 my %saved_task = %$task;
792 eval { $plugin->prepare ($task, $vmid, $mode); };
793 if (my $err = $@) {
794 die $err if $err !~ m/^mode failure/;
795 debugmsg ('info', $err, $logfd);
796 debugmsg ('info', "trying 'suspend' mode instead", $logfd);
797 $mode = 'suspend'; # so prepare is called again below
798 %$task = %saved_task;
799 }
800 }
801
802 $task->{mode} = $mode;
803
804 debugmsg ('info', "backup mode: $mode", $logfd);
805
806 debugmsg ('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
807 if $opts->{bwlimit};
808
809 debugmsg ('info', "ionice priority: $opts->{ionice}", $logfd);
810
811 if ($mode eq 'stop') {
812
813 $plugin->prepare ($task, $vmid, $mode);
814
815 $self->run_hook_script ('backup-start', $task, $logfd);
816
817 if ($running) {
818 debugmsg ('info', "stopping vm", $logfd);
819 $vmstoptime = time ();
820 $self->run_hook_script ('pre-stop', $task, $logfd);
821 $plugin->stop_vm ($task, $vmid);
822 $cleanup->{restart} = 1;
823 }
824
825
826 } elsif ($mode eq 'suspend') {
827
828 $plugin->prepare ($task, $vmid, $mode);
829
830 $self->run_hook_script ('backup-start', $task, $logfd);
831
832 if ($vmtype eq 'openvz') {
833 # pre-suspend rsync
834 $plugin->copy_data_phase1 ($task, $vmid);
835 }
836
837 debugmsg ('info', "suspend vm", $logfd);
838 $vmstoptime = time ();
839 $self->run_hook_script ('pre-stop', $task, $logfd);
840 $plugin->suspend_vm ($task, $vmid);
841 $cleanup->{resume} = 1;
842
843 if ($vmtype eq 'openvz') {
844 # post-suspend rsync
845 $plugin->copy_data_phase2 ($task, $vmid);
846
847 debugmsg ('info', "resume vm", $logfd);
848 $cleanup->{resume} = 0;
849 $self->run_hook_script ('pre-restart', $task, $logfd);
850 $plugin->resume_vm ($task, $vmid);
851 my $delay = time () - $vmstoptime;
852 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
853 }
854
855 } elsif ($mode eq 'snapshot') {
856
c5be0f8c
DM
857 $self->run_hook_script ('backup-start', $task, $logfd);
858
aaeeeebe
DM
859 my $snapshot_count = $task->{snapshot_count} || 0;
860
861 $self->run_hook_script ('pre-stop', $task, $logfd);
862
863 if ($snapshot_count > 1) {
864 debugmsg ('info', "suspend vm to make snapshot", $logfd);
865 $vmstoptime = time ();
866 $plugin->suspend_vm ($task, $vmid);
867 $cleanup->{resume} = 1;
868 }
869
870 $plugin->snapshot ($task, $vmid);
871
872 $self->run_hook_script ('pre-restart', $task, $logfd);
873
874 if ($snapshot_count > 1) {
875 debugmsg ('info', "resume vm", $logfd);
876 $cleanup->{resume} = 0;
877 $plugin->resume_vm ($task, $vmid);
878 my $delay = time () - $vmstoptime;
879 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
880 }
881
882 } else {
883 die "internal error - unknown mode '$mode'\n";
884 }
885
886 # assemble archive image
887 $plugin->assemble ($task, $vmid);
888
889 # produce archive
890
891 if ($opts->{stdout}) {
892 debugmsg ('info', "sending archive to stdout", $logfd);
d7550e09 893 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
894 $self->run_hook_script ('backup-end', $task, $logfd);
895 return;
896 }
897
898 debugmsg ('info', "creating archive '$task->{tarfile}'", $logfd);
d7550e09 899 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
900
901 rename ($task->{tmptar}, $task->{tarfile}) ||
902 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
903
904 # determine size
905 $task->{size} = (-s $task->{tarfile}) || 0;
906 my $cs = format_size ($task->{size});
907 debugmsg ('info', "archive file size: $cs", $logfd);
908
909 # purge older backup
910
899b8373
DM
911 if ($maxfiles && $opts->{remove}) {
912 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname, $task->{tarfile});
913 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
aaeeeebe 914
899b8373
DM
915 while (scalar (@$bklist) >= $maxfiles) {
916 my $d = pop @$bklist;
aaeeeebe
DM
917 debugmsg ('info', "delete old backup '$d->[0]'", $logfd);
918 unlink $d->[0];
919 my $logfn = $d->[0];
757fd3d5 920 $logfn =~ s/\.(tgz|((tar|vma)(\.(gz|lzo))?))$/\.log/;
aaeeeebe
DM
921 unlink $logfn;
922 }
923 }
924
925 $self->run_hook_script ('backup-end', $task, $logfd);
926 };
927 my $err = $@;
928
929 if ($plugin) {
930 # clean-up
931
932 if ($cleanup->{unlock}) {
933 eval { $plugin->unlock_vm ($vmid); };
934 warn $@ if $@;
935 }
936
937 eval { $plugin->cleanup ($task, $vmid) };
938 warn $@ if $@;
939
940 eval { $plugin->set_logfd (undef); };
941 warn $@ if $@;
942
943 if ($cleanup->{resume} || $cleanup->{restart}) {
944 eval {
945 $self->run_hook_script ('pre-restart', $task, $logfd);
946 if ($cleanup->{resume}) {
947 debugmsg ('info', "resume vm", $logfd);
948 $plugin->resume_vm ($task, $vmid);
949 } else {
757fd3d5
DM
950 my $running = $plugin->vm_status($vmid);
951 if (!$running) {
952 debugmsg ('info', "restarting vm", $logfd);
953 $plugin->start_vm ($task, $vmid);
954 }
aaeeeebe
DM
955 }
956 };
957 my $err = $@;
958 if ($err) {
959 warn $err;
960 } else {
961 my $delay = time () - $vmstoptime;
962 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
963 }
964 }
965 }
966
967 eval { unlink $task->{tmptar} if $task->{tmptar} && -f $task->{tmptar}; };
968 warn $@ if $@;
969
970 eval { rmtree $task->{tmpdir} if $task->{tmpdir} && -d $task->{tmpdir}; };
971 warn $@ if $@;
972
973 my $delay = $task->{backuptime} = time () - $vmstarttime;
974
975 if ($err) {
976 $task->{state} = 'err';
977 $task->{msg} = $err;
978 debugmsg ('err', "Backup of VM $vmid failed - $err", $logfd, 1);
979
980 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
981
982 } else {
983 $task->{state} = 'ok';
984 my $tstr = format_time ($delay);
985 debugmsg ('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
986 }
987
988 close ($logfd) if $logfd;
989
990 if ($task->{tmplog} && $task->{logfile}) {
991 system ("cp '$task->{tmplog}' '$task->{logfile}'");
992 }
993
994 eval { $self->run_hook_script ('log-end', $task); };
995
996 die $err if $err && $err =~ m/^interrupted by signal$/;
997}
998
999sub exec_backup {
d7550e09 1000 my ($self, $rpcenv, $authuser) = @_;
aaeeeebe
DM
1001
1002 my $opts = $self->{opts};
1003
1004 debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
a7e42354
DM
1005 debugmsg ('info', "skip external VMs: " . join(', ', @{$self->{skiplist}}))
1006 if scalar(@{$self->{skiplist}});
1007
aaeeeebe
DM
1008 my $tasklist = [];
1009
1010 if ($opts->{all}) {
1011 foreach my $plugin (@{$self->{plugins}}) {
1012 my $vmlist = $plugin->vmlist();
1013 foreach my $vmid (sort @$vmlist) {
1014 next if grep { $_ eq $vmid } @{$opts->{exclude}};
98e84b16 1015 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
aaeeeebe
DM
1016 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin };
1017 }
1018 }
1019 } else {
1020 foreach my $vmid (sort @{$opts->{vmids}}) {
1021 my $plugin;
1022 foreach my $pg (@{$self->{plugins}}) {
1023 my $vmlist = $pg->vmlist();
1024 if (grep { $_ eq $vmid } @$vmlist) {
1025 $plugin = $pg;
1026 last;
1027 }
1028 }
98e84b16 1029 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
aaeeeebe
DM
1030 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin };
1031 }
1032 }
1033
1034 my $starttime = time();
1035 my $errcount = 0;
1036 eval {
1037
1038 $self->run_hook_script ('job-start');
1039
1040 foreach my $task (@$tasklist) {
1041 $self->exec_backup_task ($task);
1042 $errcount += 1 if $task->{state} ne 'ok';
1043 }
1044
1045 $self->run_hook_script ('job-end');
1046 };
1047 my $err = $@;
1048
1049 $self->run_hook_script ('job-abort') if $err;
1050
1051 if ($err) {
1052 debugmsg ('err', "Backup job failed - $err", undef, 1);
1053 } else {
1054 if ($errcount) {
1055 debugmsg ('info', "Backup job finished with errors", undef, 1);
1056 } else {
61ca4432 1057 debugmsg ('info', "Backup job finished successfully", undef, 1);
aaeeeebe
DM
1058 }
1059 }
1060
1061 my $totaltime = time() - $starttime;
1062
1063 eval { $self->$sendmail ($tasklist, $totaltime); };
1064 debugmsg ('err', $@) if $@;
4a4051d8
DM
1065
1066 die $err if $err;
1067
1068 die "job errors\n" if $errcount;
aaeeeebe
DM
1069}
1070
ac27b58d
DM
1071my $confdesc = {
1072 vmid => {
1073 type => 'string', format => 'pve-vmid-list',
1074 description => "The ID of the VM you want to backup.",
1075 optional => 1,
1076 },
1077 node => get_standard_option('pve-node', {
1078 description => "Only run if executed on this node.",
1079 optional => 1,
1080 }),
1081 all => {
1082 type => 'boolean',
1083 description => "Backup all known VMs on this host.",
1084 optional => 1,
1085 default => 0,
1086 },
1087 stdexcludes => {
1088 type => 'boolean',
1089 description => "Exclude temorary files and logs.",
1090 optional => 1,
1091 default => 1,
1092 },
1093 compress => {
d7550e09
DM
1094 type => 'string',
1095 description => "Compress dump file.",
ac27b58d 1096 optional => 1,
d7550e09
DM
1097 enum => ['0', '1', 'gzip', 'lzo'],
1098 default => 'lzo',
ac27b58d
DM
1099 },
1100 quiet => {
1101 type => 'boolean',
1102 description => "Be quiet.",
1103 optional => 1,
1104 default => 0,
1105 },
47664cbe
DM
1106 mode => {
1107 type => 'string',
1108 description => "Backup mode.",
ac27b58d 1109 optional => 1,
47664cbe
DM
1110 default => 'stop',
1111 enum => [ 'snapshot', 'suspend', 'stop' ],
ac27b58d
DM
1112 },
1113 exclude => {
1114 type => 'string', format => 'pve-vmid-list',
1115 description => "exclude specified VMs (assumes --all)",
1116 optional => 1,
1117 },
1118 'exclude-path' => {
1119 type => 'string', format => 'string-alist',
1120 description => "exclude certain files/directories (regex).",
1121 optional => 1,
1122 },
1123 mailto => {
1124 type => 'string', format => 'string-list',
1125 description => "",
1126 optional => 1,
1127 },
1128 tmpdir => {
1129 type => 'string',
1130 description => "Store temporary files to specified directory.",
1131 optional => 1,
1132 },
1133 dumpdir => {
1134 type => 'string',
1135 description => "Store resulting files to specified directory.",
1136 optional => 1,
1137 },
1138 script => {
1139 type => 'string',
1140 description => "Use specified hook script.",
1141 optional => 1,
1142 },
1143 storage => get_standard_option('pve-storage-id', {
1144 description => "Store resulting file to this storage.",
1145 optional => 1,
1146 }),
1147 size => {
1148 type => 'integer',
1149 description => "LVM snapshot size im MB.",
1150 optional => 1,
1151 minimum => 500,
1152 },
1153 bwlimit => {
1154 type => 'integer',
1155 description => "Limit I/O bandwidth (KBytes per second).",
1156 optional => 1,
1157 minimum => 0,
1158 },
1159 ionice => {
1160 type => 'integer',
1161 description => "Set CFQ ionice priority.",
1162 optional => 1,
1163 minimum => 0,
1164 maximum => 8,
1165 },
1166 lockwait => {
1167 type => 'integer',
1168 description => "Maximal time to wait for the global lock (minutes).",
1169 optional => 1,
1170 minimum => 0,
1171 },
1172 stopwait => {
1173 type => 'integer',
1174 description => "Maximal time to wait until a VM is stopped (minutes).",
1175 optional => 1,
1176 minimum => 0,
1177 },
1178 maxfiles => {
1179 type => 'integer',
1180 description => "Maximal number of backup files per VM.",
1181 optional => 1,
1182 minimum => 1,
1183 },
899b8373
DM
1184 remove => {
1185 type => 'boolean',
1186 description => "Remove old backup files if there are more than 'maxfiles' backup files.",
1187 optional => 1,
1188 default => 1,
1189 },
ac27b58d
DM
1190};
1191
47664cbe
DM
1192sub option_exists {
1193 my $key = shift;
1194 return defined($confdesc->{$key});
1195}
1196
ac27b58d
DM
1197# add JSON properties for create and set function
1198sub json_config_properties {
1199 my $prop = shift;
1200
1201 foreach my $opt (keys %$confdesc) {
1202 $prop->{$opt} = $confdesc->{$opt};
1203 }
1204
1205 return $prop;
1206}
1207
31aef761
DM
1208sub verify_vzdump_parameters {
1209 my ($param, $check_missing) = @_;
1210
1211 raise_param_exc({ all => "option conflicts with option 'vmid'"})
1212 if $param->{all} && $param->{vmid};
1213
1214 raise_param_exc({ exclude => "option conflicts with option 'vmid'"})
1215 if $param->{exclude} && $param->{vmid};
1216
1217 $param->{all} = 1 if defined($param->{exclude});
1218
1219 return if !$check_missing;
1220
1221 raise_param_exc({ vmid => "property is missing"})
1222 if !$param->{all} && !$param->{vmid};
1223
1224}
1225
1226sub command_line {
1227 my ($param) = @_;
1228
1229 my $cmd = "vzdump";
1230
1231 if ($param->{vmid}) {
1232 $cmd .= " " . join(' ', PVE::Tools::split_list($param->{vmid}));
1233 }
1234
1235 foreach my $p (keys %$param) {
59af6aee 1236 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' || $p eq 'dow' || $p eq 'stdout';
31aef761
DM
1237 my $v = $param->{$p};
1238 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
f4a8bab4
DM
1239 if ($p eq 'exclude-path') {
1240 foreach my $path (split(/\0/, $v || '')) {
1241 $cmd .= " --$p " . PVE::Tools::shellquote($path);
1242 }
1243 } else {
1244 $cmd .= " --$p " . PVE::Tools::shellquote($v) if defined($v) && $v ne '';
1245 }
31aef761
DM
1246 }
1247
1248 return $cmd;
1249}
1250
aaeeeebe 12511;