]> git.proxmox.com Git - qemu-server.git/blob - PVE/VZDump/QemuServer.pm
Fix #879: exclusion of disk for backup
[qemu-server.git] / PVE / VZDump / QemuServer.pm
1 package PVE::VZDump::QemuServer;
2
3 use strict;
4 use warnings;
5 use File::Path;
6 use File::Basename;
7 use PVE::INotify;
8 use PVE::VZDump;
9 use PVE::IPCC;
10 use PVE::Cluster qw(cfs_read_file);
11 use PVE::Tools;
12 use PVE::Storage::Plugin;
13 use PVE::Storage;
14 use PVE::QemuServer;
15 use IO::File;
16 use IPC::Open3;
17
18 use base qw (PVE::VZDump::Plugin);
19
20 sub new {
21 my ($class, $vzdump) = @_;
22
23 PVE::VZDump::check_bin('qm');
24
25 my $self = bless { vzdump => $vzdump };
26
27 $self->{vmlist} = PVE::QemuServer::vzlist();
28 $self->{storecfg} = PVE::Storage::config();
29
30 return $self;
31 };
32
33
34 sub type {
35 return 'qemu';
36 }
37
38 sub vmlist {
39 my ($self) = @_;
40
41 return [ keys %{$self->{vmlist}} ];
42 }
43
44 sub prepare {
45 my ($self, $task, $vmid, $mode) = @_;
46
47 $task->{disks} = [];
48
49 my $conf = $self->{vmlist}->{$vmid} = PVE::QemuServer::load_config($vmid);
50
51 $self->{vm_was_running} = 1;
52 if (!PVE::QemuServer::check_running($vmid)) {
53 $self->{vm_was_running} = 0;
54 }
55
56 $task->{hostname} = $conf->{name};
57
58 my $hostname = PVE::INotify::nodename();
59
60 my $vollist = [];
61 my $drivehash = {};
62 PVE::QemuServer::foreach_drive($conf, sub {
63 my ($ds, $drive) = @_;
64
65 return if PVE::QemuServer::drive_is_cdrom($drive);
66
67 if (defined($drive->{backup}) && !$drive->{backup}) {
68 $self->loginfo("exclude disk '$ds' (backup=no)");
69 return;
70 } elsif ($drive->{iothread}) {
71 die "disk '$ds' (iothread=on) can't use backup feature currently. Please set backup=no for this drive";
72 }
73
74 my $volid = $drive->{file};
75
76 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
77 push @$vollist, $volid if $storeid;
78 $drivehash->{$ds} = $drive;
79 });
80
81 PVE::Storage::activate_volumes($self->{storecfg}, $vollist);
82
83 foreach my $ds (sort keys %$drivehash) {
84 my $drive = $drivehash->{$ds};
85
86 my $volid = $drive->{file};
87
88 my $path;
89
90 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
91 if ($storeid) {
92 $path = PVE::Storage::path($self->{storecfg}, $volid);
93 } else {
94 $path = $volid;
95 }
96
97 next if !$path;
98
99 my $format = undef;
100 my $size = undef;
101
102 eval{
103 ($size, $format) = PVE::Storage::volume_size_info($self->{storecfg}, $volid, 5);
104 };
105 die "no such volume '$volid'\n" if $@;
106
107 my $diskinfo = { path => $path , volid => $volid, storeid => $storeid,
108 format => $format, virtdev => $ds, qmdevice => "drive-$ds" };
109
110 if (-b $path) {
111 $diskinfo->{type} = 'block';
112 } else {
113 $diskinfo->{type} = 'file';
114 }
115
116 push @{$task->{disks}}, $diskinfo;
117 }
118 }
119
120 sub vm_status {
121 my ($self, $vmid) = @_;
122
123 my $running = PVE::QemuServer::check_running($vmid) ? 1 : 0;
124
125 return wantarray ? ($running, $running ? 'running' : 'stopped') : $running;
126 }
127
128 sub lock_vm {
129 my ($self, $vmid) = @_;
130
131 $self->cmd ("qm set $vmid --lock backup");
132 }
133
134 sub unlock_vm {
135 my ($self, $vmid) = @_;
136
137 $self->cmd ("qm unlock $vmid");
138 }
139
140 sub stop_vm {
141 my ($self, $task, $vmid) = @_;
142
143 my $opts = $self->{vzdump}->{opts};
144
145 my $wait = $opts->{stopwait} * 60;
146 # send shutdown and wait
147 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
148 }
149
150 sub start_vm {
151 my ($self, $task, $vmid) = @_;
152
153 $self->cmd ("qm start $vmid --skiplock");
154 }
155
156 sub suspend_vm {
157 my ($self, $task, $vmid) = @_;
158
159 $self->cmd ("qm suspend $vmid --skiplock");
160 }
161
162 sub resume_vm {
163 my ($self, $task, $vmid) = @_;
164
165 $self->cmd ("qm resume $vmid --skiplock");
166 }
167
168 sub assemble {
169 my ($self, $task, $vmid) = @_;
170
171 my $conffile = PVE::QemuServer::config_file ($vmid);
172
173 my $outfile = "$task->{tmpdir}/qemu-server.conf";
174 my $firewall_src = "/etc/pve/firewall/$vmid.fw";
175 my $firewall_dest = "$task->{tmpdir}/qemu-server.fw";
176
177 my $outfd = IO::File->new (">$outfile") ||
178 die "unable to open '$outfile'";
179 my $conffd = IO::File->new ($conffile, 'r') ||
180 die "unable open '$conffile'";
181
182 my $found_snapshot;
183 while (defined (my $line = <$conffd>)) {
184 next if $line =~ m/^\#vzdump\#/; # just to be sure
185 next if $line =~ m/^\#qmdump\#/; # just to be sure
186 if ($line =~ m/^\[.*\]\s*$/) {
187 $found_snapshot = 1;
188 }
189 next if $found_snapshot; # skip all snapshots data
190 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
191 $self->loginfo("skip unused drive '$1' (not included into backup)");
192 next;
193 }
194 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
195
196 print $outfd $line;
197 }
198
199 foreach my $di (@{$task->{disks}}) {
200 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
201 my $storeid = $di->{storeid} || '';
202 my $format = $di->{format} || '';
203 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
204 } else {
205 die "internal error";
206 }
207 }
208
209 if ($found_snapshot) {
210 $self->loginfo("snapshots found (not included into backup)");
211 }
212
213 PVE::Tools::file_copy($firewall_src, $firewall_dest) if -f $firewall_src;
214 }
215
216 sub archive {
217 my ($self, $task, $vmid, $filename, $comp) = @_;
218
219 my $conffile = "$task->{tmpdir}/qemu-server.conf";
220 my $firewall = "$task->{tmpdir}/qemu-server.fw";
221
222 my $opts = $self->{vzdump}->{opts};
223
224 my $starttime = time ();
225
226 my $speed = 0;
227 if ($opts->{bwlimit}) {
228 $speed = $opts->{bwlimit}*1024;
229 }
230
231 my $diskcount = scalar(@{$task->{disks}});
232
233 if (PVE::QemuServer::is_template($self->{vmlist}->{$vmid}) || !$diskcount) {
234 my @pathlist;
235 foreach my $di (@{$task->{disks}}) {
236 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
237 push @pathlist, "$di->{qmdevice}=$di->{path}";
238 } else {
239 die "implement me";
240 }
241 }
242
243 if (!$diskcount) {
244 $self->loginfo("backup contains no disks");
245 }
246
247 my $outcmd;
248 if ($comp) {
249 $outcmd = "exec:$comp";
250 } else {
251 $outcmd = "exec:cat";
252 }
253
254 $outcmd .= ">$filename" if !$opts->{stdout};
255
256 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
257 push @$cmd, '-c', $firewall if -e $firewall;
258 push @$cmd, $outcmd, @pathlist;
259
260 $self->loginfo("starting template backup");
261 $self->loginfo(join(' ', @$cmd));
262
263 if ($opts->{stdout}) {
264 $self->cmd($cmd, output => ">&=" . fileno($opts->{stdout}));
265 } else {
266 $self->cmd($cmd);
267 }
268
269 return;
270 }
271
272
273 my $devlist = '';
274 foreach my $di (@{$task->{disks}}) {
275 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
276 $devlist .= $devlist ? ",$di->{qmdevice}" : $di->{qmdevice};
277 } else {
278 die "implement me";
279 }
280 }
281
282 my $stop_after_backup;
283 my $resume_on_backup;
284
285 my $skiplock = 1;
286 my $vm_is_running = PVE::QemuServer::check_running($vmid);
287 if (!$vm_is_running) {
288 eval {
289 $self->loginfo("starting kvm to execute backup task");
290 PVE::QemuServer::vm_start($self->{storecfg}, $vmid, undef,
291 $skiplock, undef, 1);
292 if ($self->{vm_was_running}) {
293 $resume_on_backup = 1;
294 } else {
295 $stop_after_backup = 1;
296 }
297 };
298 if (my $err = $@) {
299 die $err;
300 }
301 }
302
303 my $cpid;
304 my $interrupt_msg = "interrupted by signal\n";
305 eval {
306 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = $SIG{PIPE} = sub {
307 die $interrupt_msg;
308 };
309
310 my $qmpclient = PVE::QMPClient->new();
311
312 my $uuid;
313
314 my $backup_cb = sub {
315 my ($vmid, $resp) = @_;
316 $uuid = $resp->{return}->{UUID};
317 };
318
319 my $outfh;
320 if ($opts->{stdout}) {
321 $outfh = $opts->{stdout};
322 } else {
323 $outfh = IO::File->new($filename, "w") ||
324 die "unable to open file '$filename' - $!\n";
325 }
326
327 my $outfileno;
328 if ($comp) {
329 my @pipefd = POSIX::pipe();
330 $cpid = fork();
331 die "unable to fork worker - $!" if !defined($cpid);
332 if ($cpid == 0) {
333 eval {
334 POSIX::close($pipefd[1]);
335 # redirect STDIN
336 my $fd = fileno(STDIN);
337 close STDIN;
338 POSIX::close(0) if $fd != 0;
339 die "unable to redirect STDIN - $!"
340 if !open(STDIN, "<&", $pipefd[0]);
341
342 # redirect STDOUT
343 $fd = fileno(STDOUT);
344 close STDOUT;
345 POSIX::close (1) if $fd != 1;
346
347 die "unable to redirect STDOUT - $!"
348 if !open(STDOUT, ">&", fileno($outfh));
349
350 exec($comp);
351 die "fork compressor '$comp' failed\n";
352 };
353 if (my $err = $@) {
354 $self->logerr($err);
355 POSIX::_exit(1);
356 }
357 POSIX::_exit(0);
358 kill(-9, $$);
359 } else {
360 POSIX::close($pipefd[0]);
361 $outfileno = $pipefd[1];
362 }
363 } else {
364 $outfileno = fileno($outfh);
365 }
366
367 my $add_fd_cb = sub {
368 my ($vmid, $resp) = @_;
369
370 my $params = {
371 'backup-file' => "/dev/fdname/backup",
372 speed => $speed,
373 'config-file' => $conffile,
374 devlist => $devlist
375 };
376
377 $params->{'firewall-file'} = $firewall if -e $firewall;
378 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
379 };
380
381 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd',
382 fd => $outfileno, fdname => "backup");
383
384 if ($self->{vmlist}->{$vmid}->{agent} && $vm_is_running){
385 eval { PVE::QemuServer::vm_mon_cmd($vmid, "guest-fsfreeze-freeze"); };
386 if (my $err = $@) {
387 $self->logerr($err);
388 }
389 }
390
391 $qmpclient->queue_execute();
392
393 if ($self->{vmlist}->{$vmid}->{agent} && $vm_is_running ){
394 eval { PVE::QemuServer::vm_mon_cmd($vmid, "guest-fsfreeze-thaw"); };
395 if (my $err = $@) {
396 $self->logerr($err);
397 }
398 }
399 die $qmpclient->{errors}->{$vmid} if $qmpclient->{errors}->{$vmid};
400
401 if ($cpid) {
402 POSIX::close($outfileno) == 0 ||
403 die "close output file handle failed\n";
404 }
405
406 die "got no uuid for backup task\n" if !$uuid;
407
408 $self->loginfo("started backup task '$uuid'");
409
410 if ($resume_on_backup) {
411 $self->loginfo("resume VM");
412 PVE::QemuServer::vm_mon_cmd($vmid, 'cont');
413 }
414
415 my $status;
416 my $starttime = time ();
417 my $last_per = -1;
418 my $last_total = 0;
419 my $last_zero = 0;
420 my $last_transferred = 0;
421 my $last_time = time();
422 my $transferred;
423
424 while(1) {
425 $status = PVE::QemuServer::vm_mon_cmd($vmid, 'query-backup');
426 my $total = $status->{total} || 0;
427 $transferred = $status->{transferred} || 0;
428 my $per = $total ? int(($transferred * 100)/$total) : 0;
429 my $zero = $status->{'zero-bytes'} || 0;
430 my $zero_per = $total ? int(($zero * 100)/$total) : 0;
431
432 die "got unexpected uuid\n" if !$status->{uuid} || ($status->{uuid} ne $uuid);
433
434 my $ctime = time();
435 my $duration = $ctime - $starttime;
436
437 my $rbytes = $transferred - $last_transferred;
438 my $wbytes = $rbytes - ($zero - $last_zero);
439
440 my $timediff = ($ctime - $last_time) || 1; # fixme
441 my $mbps_read = ($rbytes > 0) ?
442 int(($rbytes/$timediff)/(1000*1000)) : 0;
443 my $mbps_write = ($wbytes > 0) ?
444 int(($wbytes/$timediff)/(1000*1000)) : 0;
445
446 my $statusline = "status: $per% ($transferred/$total), " .
447 "sparse ${zero_per}% ($zero), duration $duration, " .
448 "$mbps_read/$mbps_write MB/s";
449 my $res = $status->{status} || 'unknown';
450 if ($res ne 'active') {
451 $self->loginfo($statusline);
452 die(($status->{errmsg} || "unknown error") . "\n")
453 if $res eq 'error';
454 die "got unexpected status '$res'\n"
455 if $res ne 'done';
456 die "got wrong number of transfered bytes ($total != $transferred)\n"
457 if ($res eq 'done') && ($total != $transferred);
458
459 last;
460 }
461 if ($per != $last_per && ($timediff > 2)) {
462 $self->loginfo($statusline);
463 $last_per = $per;
464 $last_total = $total if $total;
465 $last_zero = $zero if $zero;
466 $last_transferred = $transferred if $transferred;
467 $last_time = $ctime;
468 }
469 sleep(1);
470 }
471
472 my $duration = time() - $starttime;
473 if ($transferred && $duration) {
474 my $mb = int($transferred/(1000*1000));
475 my $mbps = int(($transferred/$duration)/(1000*1000));
476 $self->loginfo("transferred $mb MB in $duration seconds ($mbps MB/s)");
477 }
478 };
479 my $err = $@;
480
481 if ($err) {
482 $self->logerr($err);
483 $self->loginfo("aborting backup job");
484 eval { PVE::QemuServer::vm_mon_cmd($vmid, 'backup-cancel'); };
485 if (my $err1 = $@) {
486 $self->logerr($err1);
487 }
488 }
489
490 if ($stop_after_backup) {
491 # stop if not running
492 eval {
493 my $resp = PVE::QemuServer::vm_mon_cmd($vmid, 'query-status');
494 my $status = $resp && $resp->{status} ? $resp->{status} : 'unknown';
495 if ($status eq 'prelaunch') {
496 $self->loginfo("stopping kvm after backup task");
497 PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, $skiplock);
498 } else {
499 $self->loginfo("kvm status changed after backup ('$status')" .
500 " - keep VM running");
501 }
502 }
503 }
504
505 if ($err) {
506 if ($cpid) {
507 kill(9, $cpid);
508 waitpid($cpid, 0);
509 }
510 die $err;
511 }
512
513 if ($cpid && (waitpid($cpid, 0) > 0)) {
514 my $stat = $?;
515 my $ec = $stat >> 8;
516 my $signal = $stat & 127;
517 if ($ec || $signal) {
518 die "$comp failed - wrong exit status $ec" .
519 ($signal ? " (signal $signal)\n" : "\n");
520 }
521 }
522 }
523
524 sub snapshot {
525 my ($self, $task, $vmid) = @_;
526
527 # nothing to do
528 }
529
530 sub cleanup {
531 my ($self, $task, $vmid) = @_;
532
533 # nothing to do ?
534 }
535
536 1;