]> git.proxmox.com Git - qemu-server.git/blob - PVE/VZDump/QemuServer.pm
white space cleanups
[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} eq "no") {
68 $self->loginfo("exclude disk '$ds' (backup=no)");
69 return;
70 }
71
72 my $volid = $drive->{file};
73
74 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
75 push @$vollist, $volid if $storeid;
76 $drivehash->{$ds} = $drive;
77 });
78
79 PVE::Storage::activate_volumes($self->{storecfg}, $vollist);
80
81 foreach my $ds (sort keys %$drivehash) {
82 my $drive = $drivehash->{$ds};
83
84 my $volid = $drive->{file};
85
86 my $path;
87
88 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
89 if ($storeid) {
90 $path = PVE::Storage::path($self->{storecfg}, $volid);
91 } else {
92 $path = $volid;
93 }
94
95 next if !$path;
96
97 my $format = undef;
98 my $size = undef;
99
100 eval{
101 ($size, $format) = PVE::Storage::volume_size_info($self->{storecfg}, $volid, 5);
102 };
103 die "no such volume '$volid'\n" if $@;
104
105 my $diskinfo = { path => $path , volid => $volid, storeid => $storeid,
106 format => $format, virtdev => $ds, qmdevice => "drive-$ds" };
107
108 if (-b $path) {
109 $diskinfo->{type} = 'block';
110 } else {
111 $diskinfo->{type} = 'file';
112 }
113
114 push @{$task->{disks}}, $diskinfo;
115 }
116 }
117
118 sub vm_status {
119 my ($self, $vmid) = @_;
120
121 my $running = PVE::QemuServer::check_running($vmid) ? 1 : 0;
122
123 return wantarray ? ($running, $running ? 'running' : 'stopped') : $running;
124 }
125
126 sub lock_vm {
127 my ($self, $vmid) = @_;
128
129 $self->cmd ("qm set $vmid --lock backup");
130 }
131
132 sub unlock_vm {
133 my ($self, $vmid) = @_;
134
135 $self->cmd ("qm unlock $vmid");
136 }
137
138 sub stop_vm {
139 my ($self, $task, $vmid) = @_;
140
141 my $opts = $self->{vzdump}->{opts};
142
143 my $wait = $opts->{stopwait} * 60;
144 # send shutdown and wait
145 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
146 }
147
148 sub start_vm {
149 my ($self, $task, $vmid) = @_;
150
151 $self->cmd ("qm start $vmid --skiplock");
152 }
153
154 sub suspend_vm {
155 my ($self, $task, $vmid) = @_;
156
157 $self->cmd ("qm suspend $vmid --skiplock");
158 }
159
160 sub resume_vm {
161 my ($self, $task, $vmid) = @_;
162
163 $self->cmd ("qm resume $vmid --skiplock");
164 }
165
166 sub assemble {
167 my ($self, $task, $vmid) = @_;
168
169 my $conffile = PVE::QemuServer::config_file ($vmid);
170
171 my $outfile = "$task->{tmpdir}/qemu-server.conf";
172
173 my $outfd;
174 my $conffd;
175
176 eval {
177
178 $outfd = IO::File->new (">$outfile") ||
179 die "unable to open '$outfile'";
180 $conffd = IO::File->new ($conffile, 'r') ||
181 die "unable open '$conffile'";
182
183 my $found_snapshot;
184 while (defined (my $line = <$conffd>)) {
185 next if $line =~ m/^\#vzdump\#/; # just to be sure
186 next if $line =~ m/^\#qmdump\#/; # just to be sure
187 if ($line =~ m/^\[.*\]\s*$/) {
188 $found_snapshot = 1;
189 }
190 next if $found_snapshot; # skip all snapshots data
191 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
192 $self->loginfo("skip unused drive '$1' (not included into backup)");
193 next;
194 }
195 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
196
197 print $outfd $line;
198 }
199
200 foreach my $di (@{$task->{disks}}) {
201 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
202 my $storeid = $di->{storeid} || '';
203 my $format = $di->{format} || '';
204 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
205 } else {
206 die "internal error";
207 }
208 }
209
210 if ($found_snapshot) {
211 $self->loginfo("snapshots found (not included into backup)");
212 }
213 };
214 my $err = $@;
215
216 close ($outfd) if $outfd;
217 close ($conffd) if $conffd;
218
219 die $err if $err;
220 }
221
222 sub archive {
223 my ($self, $task, $vmid, $filename, $comp) = @_;
224
225 my $conffile = "$task->{tmpdir}/qemu-server.conf";
226
227 my $opts = $self->{vzdump}->{opts};
228
229 my $starttime = time ();
230
231 my $speed = 0;
232 if ($opts->{bwlimit}) {
233 $speed = $opts->{bwlimit}*1024;
234 }
235
236 my $diskcount = scalar(@{$task->{disks}});
237
238 if (PVE::QemuServer::is_template($self->{vmlist}->{$vmid}) || !$diskcount) {
239 my @pathlist;
240 foreach my $di (@{$task->{disks}}) {
241 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
242 push @pathlist, "$di->{qmdevice}=$di->{path}";
243 } else {
244 die "implement me";
245 }
246 }
247
248 if (!$diskcount) {
249 $self->loginfo("backup contains no disks");
250 }
251
252 my $outcmd;
253 if ($comp) {
254 $outcmd = "exec:$comp";
255 } else {
256 $outcmd = "exec:cat";
257 }
258
259 $outcmd .= ">$filename" if !$opts->{stdout};
260
261 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile, $outcmd, @pathlist];
262
263 $self->loginfo("starting template backup");
264 $self->loginfo(join(' ', @$cmd));
265
266 if ($opts->{stdout}) {
267 $self->cmd($cmd, output => ">&=" . fileno($opts->{stdout}));
268 } else {
269 $self->cmd($cmd);
270 }
271
272 return;
273 }
274
275
276 my $devlist = '';
277 foreach my $di (@{$task->{disks}}) {
278 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
279 $devlist .= $devlist ? ",$di->{qmdevice}" : $di->{qmdevice};
280 } else {
281 die "implement me";
282 }
283 }
284
285 my $stop_after_backup;
286 my $resume_on_backup;
287
288 my $skiplock = 1;
289 my $vm_is_running = PVE::QemuServer::check_running($vmid);
290 if (!$vm_is_running) {
291 eval {
292 $self->loginfo("starting kvm to execute backup task");
293 PVE::QemuServer::vm_start($self->{storecfg}, $vmid, undef,
294 $skiplock, undef, 1);
295 if ($self->{vm_was_running}) {
296 $resume_on_backup = 1;
297 } else {
298 $stop_after_backup = 1;
299 }
300 };
301 if (my $err = $@) {
302 die $err;
303 }
304 }
305
306 my $cpid;
307 my $interrupt_msg = "interrupted by signal\n";
308 eval {
309 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = $SIG{PIPE} = sub {
310 die $interrupt_msg;
311 };
312
313 my $qmpclient = PVE::QMPClient->new();
314
315 my $uuid;
316
317 my $backup_cb = sub {
318 my ($vmid, $resp) = @_;
319 $uuid = $resp->{return};
320 };
321
322 my $outfh;
323 if ($opts->{stdout}) {
324 $outfh = $opts->{stdout};
325 } else {
326 $outfh = IO::File->new($filename, "w") ||
327 die "unable to open file '$filename' - $!\n";
328 }
329
330 my $outfileno;
331 if ($comp) {
332 my @pipefd = POSIX::pipe();
333 $cpid = fork();
334 die "unable to fork worker - $!" if !defined($cpid);
335 if ($cpid == 0) {
336 eval {
337 POSIX::close($pipefd[1]);
338 # redirect STDIN
339 my $fd = fileno(STDIN);
340 close STDIN;
341 POSIX::close(0) if $fd != 0;
342 die "unable to redirect STDIN - $!"
343 if !open(STDIN, "<&", $pipefd[0]);
344
345 # redirect STDOUT
346 $fd = fileno(STDOUT);
347 close STDOUT;
348 POSIX::close (1) if $fd != 1;
349
350 die "unable to redirect STDOUT - $!"
351 if !open(STDOUT, ">&", fileno($outfh));
352
353 exec($comp);
354 die "fork compressor '$comp' failed\n";
355 };
356 if (my $err = $@) {
357 $self->logerr($err);
358 POSIX::_exit(1);
359 }
360 POSIX::_exit(0);
361 kill(-9, $$);
362 } else {
363 POSIX::close($pipefd[0]);
364 $outfileno = $pipefd[1];
365 }
366 } else {
367 $outfileno = fileno($outfh);
368 }
369
370 my $add_fd_cb = sub {
371 my ($vmid, $resp) = @_;
372
373 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup',
374 'backup-file' => "/dev/fdname/backup",
375 speed => $speed,
376 'config-file' => $conffile,
377 devlist => $devlist);
378 };
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;