]> git.proxmox.com Git - pve-manager.git/blame - PVE/VZDump.pm
create /var/run/dtach at pvedaemon startup
[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
899b8373
DM
443 my $maxfiles = $opts->{maxfiles};
444 $opts->{remove} = 1 if !defined($opts->{remove});
445
aaeeeebe
DM
446 foreach my $k (keys %$defaults) {
447 if ($k eq 'dumpdir' || $k eq 'storage') {
448 $opts->{$k} = $defaults->{$k} if !defined ($opts->{dumpdir}) &&
449 !defined ($opts->{storage});
450 } else {
451 $opts->{$k} = $defaults->{$k} if !defined ($opts->{$k});
452 }
453 }
454
aaeeeebe
DM
455 $opts->{dumpdir} =~ s|/+$|| if ($opts->{dumpdir});
456 $opts->{tmpdir} =~ s|/+$|| if ($opts->{tmpdir});
457
a7e42354
DM
458 $skiplist = [] if !$skiplist;
459 my $self = bless { cmdline => $cmdline, opts => $opts, skiplist => $skiplist };
aaeeeebe
DM
460
461 #always skip '.'
462 push @{$self->{findexcl}}, "'('", '-regex' , "'^\\.\$'", "')'", '-o';
463
464 $self->find_add_exclude ('-type', 's'); # skip sockets
465
f4a8bab4
DM
466 if ($defaults->{'exclude-path'}) {
467 foreach my $path (@{$defaults->{'exclude-path'}}) {
468 $self->find_add_exclude ('-regex', $path);
469 }
470 }
471
aaeeeebe
DM
472 if ($opts->{'exclude-path'}) {
473 foreach my $path (@{$opts->{'exclude-path'}}) {
474 $self->find_add_exclude ('-regex', $path);
475 }
476 }
477
478 if ($opts->{stdexcludes}) {
479 $self->find_add_exclude ('-files', '/var/log/.+');
480 $self->find_add_exclude ('-regex', '/tmp/.+');
481 $self->find_add_exclude ('-regex', '/var/tmp/.+');
482 $self->find_add_exclude ('-regex', '/var/run/.+pid');
483 }
484
485 foreach my $p (@plugins) {
486
487 my $pd = $p->new ($self);
488
489 push @{$self->{plugins}}, $pd;
aaeeeebe
DM
490 }
491
492 if (!$opts->{dumpdir} && !$opts->{storage}) {
19d5c0f2 493 $opts->{storage} = 'local';
aaeeeebe
DM
494 }
495
496 if ($opts->{storage}) {
497 my $info = storage_info ($opts->{storage});
498 $opts->{dumpdir} = $info->{dumpdir};
899b8373 499 $maxfiles = $info->{maxfiles} if !$maxfiles && $info->{maxfiles};
aaeeeebe
DM
500 } elsif ($opts->{dumpdir}) {
501 die "dumpdir '$opts->{dumpdir}' does not exist\n"
502 if ! -d $opts->{dumpdir};
503 } else {
504 die "internal error";
505 }
506
507 if ($opts->{tmpdir} && ! -d $opts->{tmpdir}) {
508 die "tmpdir '$opts->{tmpdir}' does not exist\n";
509 }
510
899b8373
DM
511 $opts->{maxfiles} = $maxfiles if $maxfiles;
512
aaeeeebe
DM
513 return $self;
514
515}
516
517sub get_lvm_mapping {
518
519 my $devmapper;
520
d93d0459
DM
521 my $cmd = ['lvs', '--units', 'm', '--separator', ':', '--noheadings',
522 '-o', 'vg_name,lv_name,lv_size' ];
523
524 my $parser = sub {
525 my $line = shift;
526 if ($line =~ m|^\s*(\S+):(\S+):(\d+(\.\d+))[Mm]$|) {
527 my $vg = $1;
528 my $lv = $2;
529 $devmapper->{"/dev/$vg/$lv"} = [$vg, $lv];
530 my $qlv = $lv;
531 $qlv =~ s/-/--/g;
532 my $qvg = $vg;
533 $qvg =~ s/-/--/g;
534 $devmapper->{"/dev/mapper/$qvg-$qlv"} = [$vg, $lv];
535 }
536 };
537
538 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
539 warn $@ if $@;
aaeeeebe
DM
540
541 return $devmapper;
542}
543
544sub get_mount_info {
545 my ($dir) = @_;
546
8572d646
DM
547 # Note: df 'available' can be negative, and percentage set to '-'
548
d93d0459 549 my $cmd = [ 'df', '-P', '-T', '-B', '1', $dir];
aaeeeebe 550
d93d0459 551 my $res;
aaeeeebe 552
d93d0459
DM
553 my $parser = sub {
554 my $line = shift;
8572d646
DM
555 if (my ($fsid, $fstype, undef, $mp) = $line =~
556 m!(\S+.*)\s+(\S+)\s+\d+\s+\-?\d+\s+\d+\s+(\d+%|-)\s+(/.*)$!) {
d93d0459
DM
557 $res = {
558 device => $fsid,
559 fstype => $fstype,
560 mountpoint => $mp,
561 };
562 }
aaeeeebe 563 };
d93d0459
DM
564
565 eval { PVE::Tools::run_command($cmd, errfunc => sub {}, outfunc => $parser); };
566 warn $@ if $@;
567
568 return $res;
aaeeeebe
DM
569}
570
571sub get_lvm_device {
572 my ($dir, $mapping) = @_;
573
5dc86eb8 574 my $info = get_mount_info($dir);
aaeeeebe
DM
575
576 return undef if !$info;
577
578 my $dev = $info->{device};
579
580 my ($vg, $lv);
581
582 ($vg, $lv) = @{$mapping->{$dev}} if defined $mapping->{$dev};
583
584 return wantarray ? ($dev, $info->{mountpoint}, $vg, $lv, $info->{fstype}) : $dev;
585}
586
587sub getlock {
588 my ($self) = @_;
589
590 my $maxwait = $self->{opts}->{lockwait} || $self->{lockwait};
591
592 if (!open (SERVER_FLCK, ">>$lockfile")) {
593 debugmsg ('err', "can't open lock on file '$lockfile' - $!", undef, 1);
594 exit (-1);
595 }
596
597 if (flock (SERVER_FLCK, LOCK_EX|LOCK_NB)) {
598 return;
599 }
600
601 if (!$maxwait) {
602 debugmsg ('err', "can't aquire lock '$lockfile' (wait = 0)", undef, 1);
603 exit (-1);
604 }
605
606 debugmsg('info', "trying to get global lock - waiting...", undef, 1);
607
608 eval {
609 alarm ($maxwait * 60);
610
611 local $SIG{ALRM} = sub { alarm (0); die "got timeout\n"; };
612
613 if (!flock (SERVER_FLCK, LOCK_EX)) {
614 my $err = $!;
615 close (SERVER_FLCK);
616 alarm (0);
617 die "$err\n";
618 }
619 alarm (0);
620 };
621 alarm (0);
622
623 my $err = $@;
624
625 if ($err) {
626 debugmsg ('err', "can't aquire lock '$lockfile' - $err", undef, 1);
627 exit (-1);
628 }
629
630 debugmsg('info', "got global lock", undef, 1);
631}
632
633sub run_hook_script {
634 my ($self, $phase, $task, $logfd) = @_;
635
636 my $opts = $self->{opts};
637
638 my $script = $opts->{script};
639
640 return if !$script;
641
642 my $cmd = "$script $phase";
643
644 $cmd .= " $task->{mode} $task->{vmid}" if ($task);
645
646 local %ENV;
647
648 foreach my $ek (qw(vmtype dumpdir hostname tarfile logfile)) {
649 $ENV{uc($ek)} = $task->{$ek} if $task->{$ek};
650 }
651
652 run_command ($logfd, $cmd);
653}
654
d7550e09
DM
655sub compressor_info {
656 my ($opt_compress) = @_;
657
658 if (!$opt_compress || $opt_compress eq '0') {
659 return undef;
660 } elsif ($opt_compress eq '1' || $opt_compress eq 'lzo') {
661 return ('lzop', 'lzo');
662 } elsif ($opt_compress eq 'gzip') {
663 return ('gzip', 'gz');
664 } else {
665 die "internal error - unknown compression option '$opt_compress'";
666 }
667}
899b8373
DM
668
669sub get_backup_file_list {
670 my ($dir, $bkname, $exclude_fn) = @_;
671
672 my $bklist = [];
673 foreach my $fn (<$dir/${bkname}-*>) {
674 next if $exclude_fn && $fn eq $exclude_fn;
675 if ($fn =~ m!/(${bkname}-(\d{4})_(\d{2})_(\d{2})-(\d{2})_(\d{2})_(\d{2})\.(tgz|(tar(\.(gz|lzo))?)))$!) {
676 $fn = "$dir/$1"; # untaint
677 my $t = timelocal ($7, $6, $5, $4, $3 - 1, $2 - 1900);
678 push @$bklist, [$fn, $t];
679 }
680 }
681
682 return $bklist;
683}
d7550e09 684
aaeeeebe
DM
685sub exec_backup_task {
686 my ($self, $task) = @_;
687
688 my $opts = $self->{opts};
689
690 my $vmid = $task->{vmid};
691 my $plugin = $task->{plugin};
692
693 my $vmstarttime = time ();
694
695 my $logfd;
696
697 my $cleanup = {};
698
699 my $vmstoptime = 0;
700
701 eval {
702 die "unable to find VM '$vmid'\n" if !$plugin;
703
704 my $vmtype = $plugin->type();
705
706 my $tmplog = "$logdir/$vmtype-$vmid.log";
707
708 my $lt = localtime();
709
710 my $bkname = "vzdump-$vmtype-$vmid";
711 my $basename = sprintf "${bkname}-%04d_%02d_%02d-%02d_%02d_%02d",
712 $lt->year + 1900, $lt->mon + 1, $lt->mday,
713 $lt->hour, $lt->min, $lt->sec;
714
899b8373
DM
715 my $maxfiles = $opts->{maxfiles};
716
717 if ($maxfiles && !$opts->{remove}) {
718 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname);
719 die "only $maxfiles backup(s) allowed - please consider to remove old backup files.\n"
720 if scalar(@$bklist) >= $maxfiles;
721 }
722
aaeeeebe
DM
723 my $logfile = $task->{logfile} = "$opts->{dumpdir}/$basename.log";
724
d7550e09
DM
725 my $ext = '.tar';
726 my ($comp, $comp_ext) = compressor_info($opts->{compress});
727 if ($comp && $comp_ext) {
728 $ext .= ".${comp_ext}";
729 }
aaeeeebe
DM
730
731 if ($opts->{stdout}) {
732 $task->{tarfile} = '-';
733 } else {
734 my $tarfile = $task->{tarfile} = "$opts->{dumpdir}/$basename$ext";
735 $task->{tmptar} = $task->{tarfile};
736 $task->{tmptar} =~ s/\.[^\.]+$/\.dat/;
737 unlink $task->{tmptar};
738 }
739
740 $task->{vmtype} = $vmtype;
741
742 if ($opts->{tmpdir}) {
743 $task->{tmpdir} = "$opts->{tmpdir}/vzdumptmp$$";
744 } else {
745 # dumpdir is posix? then use it as temporary dir
5dc86eb8 746 my $info = get_mount_info($opts->{dumpdir});
aaeeeebe
DM
747 if ($vmtype eq 'qemu' ||
748 grep ($_ eq $info->{fstype}, @posix_filesystems)) {
749 $task->{tmpdir} = "$opts->{dumpdir}/$basename.tmp";
750 } else {
751 $task->{tmpdir} = "/var/tmp/vzdumptmp$$";
752 debugmsg ('info', "filesystem type on dumpdir is '$info->{fstype}' -" .
753 "using $task->{tmpdir} for temporary files", $logfd);
754 }
755 }
756
757 rmtree $task->{tmpdir};
758 mkdir $task->{tmpdir};
759 -d $task->{tmpdir} ||
760 die "unable to create temporary directory '$task->{tmpdir}'";
761
762 $logfd = IO::File->new (">$tmplog") ||
763 die "unable to create log file '$tmplog'";
764
765 $task->{dumpdir} = $opts->{dumpdir};
766
767 $task->{tmplog} = $tmplog;
768
769 unlink $logfile;
770
771 debugmsg ('info', "Starting Backup of VM $vmid ($vmtype)", $logfd, 1);
772
773 $plugin->set_logfd ($logfd);
774
775 # test is VM is running
776 my ($running, $status_text) = $plugin->vm_status ($vmid);
777
778 debugmsg ('info', "status = ${status_text}", $logfd);
779
780 # lock VM (prevent config changes)
781 $plugin->lock_vm ($vmid);
782
783 $cleanup->{unlock} = 1;
784
785 # prepare
786
787 my $mode = $running ? $opts->{mode} : 'stop';
788
789 if ($mode eq 'snapshot') {
790 my %saved_task = %$task;
791 eval { $plugin->prepare ($task, $vmid, $mode); };
792 if (my $err = $@) {
793 die $err if $err !~ m/^mode failure/;
794 debugmsg ('info', $err, $logfd);
795 debugmsg ('info', "trying 'suspend' mode instead", $logfd);
796 $mode = 'suspend'; # so prepare is called again below
797 %$task = %saved_task;
798 }
799 }
800
801 $task->{mode} = $mode;
802
803 debugmsg ('info', "backup mode: $mode", $logfd);
804
805 debugmsg ('info', "bandwidth limit: $opts->{bwlimit} KB/s", $logfd)
806 if $opts->{bwlimit};
807
808 debugmsg ('info', "ionice priority: $opts->{ionice}", $logfd);
809
810 if ($mode eq 'stop') {
811
812 $plugin->prepare ($task, $vmid, $mode);
813
814 $self->run_hook_script ('backup-start', $task, $logfd);
815
816 if ($running) {
817 debugmsg ('info', "stopping vm", $logfd);
818 $vmstoptime = time ();
819 $self->run_hook_script ('pre-stop', $task, $logfd);
820 $plugin->stop_vm ($task, $vmid);
821 $cleanup->{restart} = 1;
822 }
823
824
825 } elsif ($mode eq 'suspend') {
826
827 $plugin->prepare ($task, $vmid, $mode);
828
829 $self->run_hook_script ('backup-start', $task, $logfd);
830
831 if ($vmtype eq 'openvz') {
832 # pre-suspend rsync
833 $plugin->copy_data_phase1 ($task, $vmid);
834 }
835
836 debugmsg ('info', "suspend vm", $logfd);
837 $vmstoptime = time ();
838 $self->run_hook_script ('pre-stop', $task, $logfd);
839 $plugin->suspend_vm ($task, $vmid);
840 $cleanup->{resume} = 1;
841
842 if ($vmtype eq 'openvz') {
843 # post-suspend rsync
844 $plugin->copy_data_phase2 ($task, $vmid);
845
846 debugmsg ('info', "resume vm", $logfd);
847 $cleanup->{resume} = 0;
848 $self->run_hook_script ('pre-restart', $task, $logfd);
849 $plugin->resume_vm ($task, $vmid);
850 my $delay = time () - $vmstoptime;
851 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
852 }
853
854 } elsif ($mode eq 'snapshot') {
855
856 my $snapshot_count = $task->{snapshot_count} || 0;
857
858 $self->run_hook_script ('pre-stop', $task, $logfd);
859
860 if ($snapshot_count > 1) {
861 debugmsg ('info', "suspend vm to make snapshot", $logfd);
862 $vmstoptime = time ();
863 $plugin->suspend_vm ($task, $vmid);
864 $cleanup->{resume} = 1;
865 }
866
867 $plugin->snapshot ($task, $vmid);
868
869 $self->run_hook_script ('pre-restart', $task, $logfd);
870
871 if ($snapshot_count > 1) {
872 debugmsg ('info', "resume vm", $logfd);
873 $cleanup->{resume} = 0;
874 $plugin->resume_vm ($task, $vmid);
875 my $delay = time () - $vmstoptime;
876 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
877 }
878
879 } else {
880 die "internal error - unknown mode '$mode'\n";
881 }
882
883 # assemble archive image
884 $plugin->assemble ($task, $vmid);
885
886 # produce archive
887
888 if ($opts->{stdout}) {
889 debugmsg ('info', "sending archive to stdout", $logfd);
d7550e09 890 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
891 $self->run_hook_script ('backup-end', $task, $logfd);
892 return;
893 }
894
895 debugmsg ('info', "creating archive '$task->{tarfile}'", $logfd);
d7550e09 896 $plugin->archive($task, $vmid, $task->{tmptar}, $comp);
aaeeeebe
DM
897
898 rename ($task->{tmptar}, $task->{tarfile}) ||
899 die "unable to rename '$task->{tmptar}' to '$task->{tarfile}'\n";
900
901 # determine size
902 $task->{size} = (-s $task->{tarfile}) || 0;
903 my $cs = format_size ($task->{size});
904 debugmsg ('info', "archive file size: $cs", $logfd);
905
906 # purge older backup
907
899b8373
DM
908 if ($maxfiles && $opts->{remove}) {
909 my $bklist = get_backup_file_list($opts->{dumpdir}, $bkname, $task->{tarfile});
910 $bklist = [ sort { $b->[1] <=> $a->[1] } @$bklist ];
aaeeeebe 911
899b8373
DM
912 while (scalar (@$bklist) >= $maxfiles) {
913 my $d = pop @$bklist;
aaeeeebe
DM
914 debugmsg ('info', "delete old backup '$d->[0]'", $logfd);
915 unlink $d->[0];
916 my $logfn = $d->[0];
d7550e09 917 $logfn =~ s/\.(tgz|(tar(\.(gz|lzo))?))$/\.log/;
aaeeeebe
DM
918 unlink $logfn;
919 }
920 }
921
922 $self->run_hook_script ('backup-end', $task, $logfd);
923 };
924 my $err = $@;
925
926 if ($plugin) {
927 # clean-up
928
929 if ($cleanup->{unlock}) {
930 eval { $plugin->unlock_vm ($vmid); };
931 warn $@ if $@;
932 }
933
934 eval { $plugin->cleanup ($task, $vmid) };
935 warn $@ if $@;
936
937 eval { $plugin->set_logfd (undef); };
938 warn $@ if $@;
939
940 if ($cleanup->{resume} || $cleanup->{restart}) {
941 eval {
942 $self->run_hook_script ('pre-restart', $task, $logfd);
943 if ($cleanup->{resume}) {
944 debugmsg ('info', "resume vm", $logfd);
945 $plugin->resume_vm ($task, $vmid);
946 } else {
947 debugmsg ('info', "restarting vm", $logfd);
948 $plugin->start_vm ($task, $vmid);
949 }
950 };
951 my $err = $@;
952 if ($err) {
953 warn $err;
954 } else {
955 my $delay = time () - $vmstoptime;
956 debugmsg ('info', "vm is online again after $delay seconds", $logfd);
957 }
958 }
959 }
960
961 eval { unlink $task->{tmptar} if $task->{tmptar} && -f $task->{tmptar}; };
962 warn $@ if $@;
963
964 eval { rmtree $task->{tmpdir} if $task->{tmpdir} && -d $task->{tmpdir}; };
965 warn $@ if $@;
966
967 my $delay = $task->{backuptime} = time () - $vmstarttime;
968
969 if ($err) {
970 $task->{state} = 'err';
971 $task->{msg} = $err;
972 debugmsg ('err', "Backup of VM $vmid failed - $err", $logfd, 1);
973
974 eval { $self->run_hook_script ('backup-abort', $task, $logfd); };
975
976 } else {
977 $task->{state} = 'ok';
978 my $tstr = format_time ($delay);
979 debugmsg ('info', "Finished Backup of VM $vmid ($tstr)", $logfd, 1);
980 }
981
982 close ($logfd) if $logfd;
983
984 if ($task->{tmplog} && $task->{logfile}) {
985 system ("cp '$task->{tmplog}' '$task->{logfile}'");
986 }
987
988 eval { $self->run_hook_script ('log-end', $task); };
989
990 die $err if $err && $err =~ m/^interrupted by signal$/;
991}
992
993sub exec_backup {
d7550e09 994 my ($self, $rpcenv, $authuser) = @_;
aaeeeebe
DM
995
996 my $opts = $self->{opts};
997
998 debugmsg ('info', "starting new backup job: $self->{cmdline}", undef, 1);
a7e42354
DM
999 debugmsg ('info', "skip external VMs: " . join(', ', @{$self->{skiplist}}))
1000 if scalar(@{$self->{skiplist}});
1001
aaeeeebe
DM
1002 my $tasklist = [];
1003
1004 if ($opts->{all}) {
1005 foreach my $plugin (@{$self->{plugins}}) {
1006 my $vmlist = $plugin->vmlist();
1007 foreach my $vmid (sort @$vmlist) {
1008 next if grep { $_ eq $vmid } @{$opts->{exclude}};
98e84b16 1009 next if !$rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ], 1);
aaeeeebe
DM
1010 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin };
1011 }
1012 }
1013 } else {
1014 foreach my $vmid (sort @{$opts->{vmids}}) {
1015 my $plugin;
1016 foreach my $pg (@{$self->{plugins}}) {
1017 my $vmlist = $pg->vmlist();
1018 if (grep { $_ eq $vmid } @$vmlist) {
1019 $plugin = $pg;
1020 last;
1021 }
1022 }
98e84b16 1023 $rpcenv->check($authuser, "/vms/$vmid", [ 'VM.Backup' ]);
aaeeeebe
DM
1024 push @$tasklist, { vmid => $vmid, state => 'todo', plugin => $plugin };
1025 }
1026 }
1027
1028 my $starttime = time();
1029 my $errcount = 0;
1030 eval {
1031
1032 $self->run_hook_script ('job-start');
1033
1034 foreach my $task (@$tasklist) {
1035 $self->exec_backup_task ($task);
1036 $errcount += 1 if $task->{state} ne 'ok';
1037 }
1038
1039 $self->run_hook_script ('job-end');
1040 };
1041 my $err = $@;
1042
1043 $self->run_hook_script ('job-abort') if $err;
1044
1045 if ($err) {
1046 debugmsg ('err', "Backup job failed - $err", undef, 1);
1047 } else {
1048 if ($errcount) {
1049 debugmsg ('info', "Backup job finished with errors", undef, 1);
1050 } else {
61ca4432 1051 debugmsg ('info', "Backup job finished successfully", undef, 1);
aaeeeebe
DM
1052 }
1053 }
1054
1055 my $totaltime = time() - $starttime;
1056
1057 eval { $self->$sendmail ($tasklist, $totaltime); };
1058 debugmsg ('err', $@) if $@;
4a4051d8
DM
1059
1060 die $err if $err;
1061
1062 die "job errors\n" if $errcount;
aaeeeebe
DM
1063}
1064
ac27b58d
DM
1065my $confdesc = {
1066 vmid => {
1067 type => 'string', format => 'pve-vmid-list',
1068 description => "The ID of the VM you want to backup.",
1069 optional => 1,
1070 },
1071 node => get_standard_option('pve-node', {
1072 description => "Only run if executed on this node.",
1073 optional => 1,
1074 }),
1075 all => {
1076 type => 'boolean',
1077 description => "Backup all known VMs on this host.",
1078 optional => 1,
1079 default => 0,
1080 },
1081 stdexcludes => {
1082 type => 'boolean',
1083 description => "Exclude temorary files and logs.",
1084 optional => 1,
1085 default => 1,
1086 },
1087 compress => {
d7550e09
DM
1088 type => 'string',
1089 description => "Compress dump file.",
ac27b58d 1090 optional => 1,
d7550e09
DM
1091 enum => ['0', '1', 'gzip', 'lzo'],
1092 default => 'lzo',
ac27b58d
DM
1093 },
1094 quiet => {
1095 type => 'boolean',
1096 description => "Be quiet.",
1097 optional => 1,
1098 default => 0,
1099 },
47664cbe
DM
1100 mode => {
1101 type => 'string',
1102 description => "Backup mode.",
ac27b58d 1103 optional => 1,
47664cbe
DM
1104 default => 'stop',
1105 enum => [ 'snapshot', 'suspend', 'stop' ],
ac27b58d
DM
1106 },
1107 exclude => {
1108 type => 'string', format => 'pve-vmid-list',
1109 description => "exclude specified VMs (assumes --all)",
1110 optional => 1,
1111 },
1112 'exclude-path' => {
1113 type => 'string', format => 'string-alist',
1114 description => "exclude certain files/directories (regex).",
1115 optional => 1,
1116 },
1117 mailto => {
1118 type => 'string', format => 'string-list',
1119 description => "",
1120 optional => 1,
1121 },
1122 tmpdir => {
1123 type => 'string',
1124 description => "Store temporary files to specified directory.",
1125 optional => 1,
1126 },
1127 dumpdir => {
1128 type => 'string',
1129 description => "Store resulting files to specified directory.",
1130 optional => 1,
1131 },
1132 script => {
1133 type => 'string',
1134 description => "Use specified hook script.",
1135 optional => 1,
1136 },
1137 storage => get_standard_option('pve-storage-id', {
1138 description => "Store resulting file to this storage.",
1139 optional => 1,
1140 }),
1141 size => {
1142 type => 'integer',
1143 description => "LVM snapshot size im MB.",
1144 optional => 1,
1145 minimum => 500,
1146 },
1147 bwlimit => {
1148 type => 'integer',
1149 description => "Limit I/O bandwidth (KBytes per second).",
1150 optional => 1,
1151 minimum => 0,
1152 },
1153 ionice => {
1154 type => 'integer',
1155 description => "Set CFQ ionice priority.",
1156 optional => 1,
1157 minimum => 0,
1158 maximum => 8,
1159 },
1160 lockwait => {
1161 type => 'integer',
1162 description => "Maximal time to wait for the global lock (minutes).",
1163 optional => 1,
1164 minimum => 0,
1165 },
1166 stopwait => {
1167 type => 'integer',
1168 description => "Maximal time to wait until a VM is stopped (minutes).",
1169 optional => 1,
1170 minimum => 0,
1171 },
1172 maxfiles => {
1173 type => 'integer',
1174 description => "Maximal number of backup files per VM.",
1175 optional => 1,
1176 minimum => 1,
1177 },
899b8373
DM
1178 remove => {
1179 type => 'boolean',
1180 description => "Remove old backup files if there are more than 'maxfiles' backup files.",
1181 optional => 1,
1182 default => 1,
1183 },
ac27b58d
DM
1184};
1185
47664cbe
DM
1186sub option_exists {
1187 my $key = shift;
1188 return defined($confdesc->{$key});
1189}
1190
ac27b58d
DM
1191# add JSON properties for create and set function
1192sub json_config_properties {
1193 my $prop = shift;
1194
1195 foreach my $opt (keys %$confdesc) {
1196 $prop->{$opt} = $confdesc->{$opt};
1197 }
1198
1199 return $prop;
1200}
1201
31aef761
DM
1202sub verify_vzdump_parameters {
1203 my ($param, $check_missing) = @_;
1204
1205 raise_param_exc({ all => "option conflicts with option 'vmid'"})
1206 if $param->{all} && $param->{vmid};
1207
1208 raise_param_exc({ exclude => "option conflicts with option 'vmid'"})
1209 if $param->{exclude} && $param->{vmid};
1210
1211 $param->{all} = 1 if defined($param->{exclude});
1212
1213 return if !$check_missing;
1214
1215 raise_param_exc({ vmid => "property is missing"})
1216 if !$param->{all} && !$param->{vmid};
1217
1218}
1219
1220sub command_line {
1221 my ($param) = @_;
1222
1223 my $cmd = "vzdump";
1224
1225 if ($param->{vmid}) {
1226 $cmd .= " " . join(' ', PVE::Tools::split_list($param->{vmid}));
1227 }
1228
1229 foreach my $p (keys %$param) {
59af6aee 1230 next if $p eq 'id' || $p eq 'vmid' || $p eq 'starttime' || $p eq 'dow' || $p eq 'stdout';
31aef761
DM
1231 my $v = $param->{$p};
1232 my $pd = $confdesc->{$p} || die "no such vzdump option '$p'\n";
f4a8bab4
DM
1233 if ($p eq 'exclude-path') {
1234 foreach my $path (split(/\0/, $v || '')) {
1235 $cmd .= " --$p " . PVE::Tools::shellquote($path);
1236 }
1237 } else {
1238 $cmd .= " --$p " . PVE::Tools::shellquote($v) if defined($v) && $v ne '';
1239 }
31aef761
DM
1240 }
1241
1242 return $cmd;
1243}
1244
aaeeeebe 12451;