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