]> git.proxmox.com Git - qemu-server.git/blame - PVE/VZDump/QemuServer.pm
vzdump: log 100% percent in case $target is 0
[qemu-server.git] / PVE / VZDump / QemuServer.pm
CommitLineData
1e3baf05
DM
1package PVE::VZDump::QemuServer;
2
1e3baf05
DM
3use strict;
4use warnings;
d610b145 5
1e3baf05 6use File::Basename;
d610b145
TL
7use File::Path;
8use IO::File;
9use IPC::Open3;
69e62894 10use JSON;
d610b145
TL
11
12use PVE::Cluster qw(cfs_read_file);
66ab1d91 13use PVE::INotify;
91bd6c90 14use PVE::IPCC;
d610b145 15use PVE::JSONSchema;
0a13e08e 16use PVE::QMPClient;
f5bdefa4 17use PVE::Storage::Plugin;
c5983223 18use PVE::Storage::PBSPlugin;
1e3baf05 19use PVE::Storage;
d610b145
TL
20use PVE::Tools;
21use PVE::VZDump;
22
912792e2 23use PVE::QemuConfig;
1e3baf05 24use PVE::QemuServer;
3392d6ca 25use PVE::QemuServer::Machine;
0a13e08e 26use PVE::QemuServer::Monitor qw(mon_cmd);
1e3baf05
DM
27
28use base qw (PVE::VZDump::Plugin);
29
30sub new {
31 my ($class, $vzdump) = @_;
874a096e 32
66ab1d91 33 PVE::VZDump::check_bin('qm');
1e3baf05 34
e2812738 35 my $self = bless { vzdump => $vzdump }, $class;
1e3baf05
DM
36
37 $self->{vmlist} = PVE::QemuServer::vzlist();
38 $self->{storecfg} = PVE::Storage::config();
39
40 return $self;
41};
42
1e3baf05
DM
43sub type {
44 return 'qemu';
45}
46
47sub vmlist {
48 my ($self) = @_;
1e3baf05
DM
49 return [ keys %{$self->{vmlist}} ];
50}
51
52sub prepare {
53 my ($self, $task, $vmid, $mode) = @_;
54
55 $task->{disks} = [];
56
ffda963f 57 my $conf = $self->{vmlist}->{$vmid} = PVE::QemuConfig->load_config($vmid);
1e3baf05 58
85b84b7b
WL
59 $self->loginfo("VM Name: $conf->{name}")
60 if defined($conf->{name});
61
91bd6c90
DM
62 $self->{vm_was_running} = 1;
63 if (!PVE::QemuServer::check_running($vmid)) {
64 $self->{vm_was_running} = 0;
585b6e28
DM
65 }
66
1e3baf05
DM
67 $task->{hostname} = $conf->{name};
68
874a096e 69 my $hostname = PVE::INotify::nodename();
1e3baf05 70
b969cc68
DM
71 my $vollist = [];
72 my $drivehash = {};
185df962 73 my $backup_volumes = PVE::QemuConfig->get_backup_volumes($conf);
1e3baf05 74
185df962
AL
75 foreach my $volume (@{$backup_volumes}) {
76 my $name = $volume->{key};
5a92276e 77 my $volume_config = $volume->{volume_config};
185df962 78 my $volid = $volume_config->{file};
1e3baf05 79
185df962
AL
80 if (!$volume->{included}) {
81 $self->loginfo("exclude disk '$name' '$volid' ($volume->{reason})");
82 next;
83 } elsif ($self->{vm_was_running} && $volume_config->{iothread}) {
3392d6ca 84 if (!PVE::QemuServer::Machine::runs_at_least_qemu_version($vmid, 4, 0, 1)) {
185df962 85 die "disk '$name' '$volid' (iothread=on) can't use backup feature with running QEMU " .
48343b3f
TL
86 "version < 4.0.1! Either set backup=no for this drive or upgrade QEMU and restart VM\n";
87 }
b53b958b 88 } else {
185df962
AL
89 my $log = "include disk '$name' '$volid'";
90 if (defined(my $size = $volume_config->{size})) {
91 my $readable_size = PVE::JSONSchema::format_size($size);
0db93c2d 92 $log .= " $readable_size";
185df962 93 }
0db93c2d 94 $self->loginfo($log);
874a096e 95 }
b969cc68 96
f5bdefa4 97 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
b969cc68 98 push @$vollist, $volid if $storeid;
185df962
AL
99 $drivehash->{$name} = $volume->{volume_config};
100 }
b969cc68
DM
101
102 PVE::Storage::activate_volumes($self->{storecfg}, $vollist);
103
075b417a
DM
104 foreach my $ds (sort keys %$drivehash) {
105 my $drive = $drivehash->{$ds};
874a096e 106
1e3baf05 107 my $volid = $drive->{file};
f5bdefa4 108 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
a113a58a
TL
109
110 my $path = $volid;
1e3baf05 111 if ($storeid) {
b969cc68 112 $path = PVE::Storage::path($self->{storecfg}, $volid);
1e3baf05 113 }
b969cc68 114 next if !$path;
1e3baf05 115
a113a58a 116 my ($size, $format) = eval { PVE::Storage::volume_size_info($self->{storecfg}, $volid, 5) };
daca220d 117 die "no such volume '$volid'\n" if $@;
91bd6c90 118
a113a58a
TL
119 my $diskinfo = {
120 path => $path,
121 volid => $volid,
122 storeid => $storeid,
123 format => $format,
124 virtdev => $ds,
125 qmdevice => "drive-$ds",
126 };
1e3baf05
DM
127
128 if (-b $path) {
1e3baf05 129 $diskinfo->{type} = 'block';
1e3baf05 130 } else {
1e3baf05 131 $diskinfo->{type} = 'file';
1e3baf05
DM
132 }
133
134 push @{$task->{disks}}, $diskinfo;
b969cc68 135 }
1e3baf05
DM
136}
137
138sub vm_status {
139 my ($self, $vmid) = @_;
140
66ab1d91 141 my $running = PVE::QemuServer::check_running($vmid) ? 1 : 0;
874a096e
DM
142
143 return wantarray ? ($running, $running ? 'running' : 'stopped') : $running;
1e3baf05
DM
144}
145
146sub lock_vm {
147 my ($self, $vmid) = @_;
148
f301bc0d 149 PVE::QemuConfig->set_lock($vmid, 'backup');
1e3baf05
DM
150}
151
152sub unlock_vm {
153 my ($self, $vmid) = @_;
154
f301bc0d 155 PVE::QemuConfig->remove_lock($vmid, 'backup');
1e3baf05
DM
156}
157
158sub stop_vm {
159 my ($self, $task, $vmid) = @_;
160
161 my $opts = $self->{vzdump}->{opts};
162
163 my $wait = $opts->{stopwait} * 60;
164 # send shutdown and wait
254575e9 165 $self->cmd ("qm shutdown $vmid --skiplock --keepActive --timeout $wait");
1e3baf05
DM
166}
167
168sub start_vm {
169 my ($self, $task, $vmid) = @_;
170
66ab1d91 171 $self->cmd ("qm start $vmid --skiplock");
1e3baf05
DM
172}
173
174sub suspend_vm {
175 my ($self, $task, $vmid) = @_;
176
66ab1d91 177 $self->cmd ("qm suspend $vmid --skiplock");
1e3baf05
DM
178}
179
180sub resume_vm {
181 my ($self, $task, $vmid) = @_;
182
66ab1d91 183 $self->cmd ("qm resume $vmid --skiplock");
1e3baf05
DM
184}
185
1e3baf05
DM
186sub assemble {
187 my ($self, $task, $vmid) = @_;
188
04096e7b 189 my $conffile = PVE::QemuConfig->config_file($vmid);
1e3baf05
DM
190
191 my $outfile = "$task->{tmpdir}/qemu-server.conf";
c05f7f3f
WL
192 my $firewall_src = "/etc/pve/firewall/$vmid.fw";
193 my $firewall_dest = "$task->{tmpdir}/qemu-server.fw";
194
195 my $outfd = IO::File->new (">$outfile") ||
196 die "unable to open '$outfile'";
197 my $conffd = IO::File->new ($conffile, 'r') ||
198 die "unable open '$conffile'";
199
200 my $found_snapshot;
391c2230 201 my $found_pending;
c05f7f3f
WL
202 while (defined (my $line = <$conffd>)) {
203 next if $line =~ m/^\#vzdump\#/; # just to be sure
204 next if $line =~ m/^\#qmdump\#/; # just to be sure
391c2230
FG
205 if ($line =~ m/^\[(.*)\]\s*$/) {
206 if ($1 =~ m/PENDING/i) {
207 $found_pending = 1;
208 } else {
209 $found_snapshot = 1;
210 }
1e3baf05 211 }
1bd6fe13 212 next if $found_snapshot || $found_pending; # skip all snapshots and pending changes config data
391c2230 213
c05f7f3f
WL
214 if ($line =~ m/^unused\d+:\s*(\S+)\s*/) {
215 $self->loginfo("skip unused drive '$1' (not included into backup)");
216 next;
1e3baf05 217 }
c05f7f3f 218 next if $line =~ m/^lock:/ || $line =~ m/^parent:/;
91bd6c90 219
c05f7f3f
WL
220 print $outfd $line;
221 }
222
223 foreach my $di (@{$task->{disks}}) {
224 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
225 my $storeid = $di->{storeid} || '';
226 my $format = $di->{format} || '';
227 print $outfd "#qmdump#map:$di->{virtdev}:$di->{qmdevice}:$storeid:$format:\n";
228 } else {
229 die "internal error";
91bd6c90 230 }
c05f7f3f 231 }
1e3baf05 232
c05f7f3f
WL
233 if ($found_snapshot) {
234 $self->loginfo("snapshots found (not included into backup)");
235 }
391c2230
FG
236 if ($found_pending) {
237 $self->loginfo("pending configuration changes found (not included into backup)");
238 }
239
c05f7f3f 240 PVE::Tools::file_copy($firewall_src, $firewall_dest) if -f $firewall_src;
1e3baf05
DM
241}
242
243sub archive {
fad02a16 244 my ($self, $task, $vmid, $filename, $comp) = @_;
1e3baf05 245
c5983223 246 my $opts = $self->{vzdump}->{opts};
c5983223
DM
247 my $scfg = $opts->{scfg};
248
69074863 249 if ($self->{vzdump}->{opts}->{pbs}) {
c5983223
DM
250 $self->archive_pbs($task, $vmid);
251 } else {
252 $self->archive_vma($task, $vmid, $filename, $comp);
253 }
254}
255
4d159c24
TL
256# number, [precision=1]
257my $num2str = sub {
258 return sprintf( "%." . ( $_[1] || 1 ) . "f", $_[0] );
259};
260sub bytes_to_human {
261 my ($bytes, $precission) = @_;
262
263 return $num2str->($bytes, $precission) . ' B' if $bytes < 1024;
264 my $kb = $bytes/1024;
265
266 return $num2str->($kb, $precission) . " KiB" if $kb < 1024;
267 my $mb = $kb/1024;
268
269 return $num2str->($mb, $precission) . " MiB" if $mb < 1024;
270 my $gb = $mb/1024;
271
272 return $num2str->($gb, $precission) . " GiB" if $gb < 1024;
273 my $tb = $gb/1024;
274
275 return $num2str->($tb, $precission) . " TiB";
276};
277
3a44897f
SR
278my $bitmap_action_to_human = sub {
279 my ($info) = @_;
280
281 my $action = $info->{action};
282
283 if ($action eq "not-used") {
284 return "disabled";
285 } elsif ($action eq "not-used-removed") {
286 return "disabled (old bitmap cleared)";
287 } elsif ($action eq "new") {
288 return "created new bitmap";
289 } elsif ($action eq "used") {
290 if ($info->{dirty} == 0) {
291 return "OK, drive clean";
292 } else {
293 my $size = bytes_to_human($info->{size});
294 my $dirty = bytes_to_human($info->{dirty});
295 return "OK, $dirty of $size dirty";
296 }
297 } elsif ($action eq "invalid") {
298 return "existing bitmap was invalid and has been cleared";
299 } else {
300 return "unknown";
301 }
302};
303
c5983223 304my $query_backup_status_loop = sub {
3a44897f 305 my ($self, $vmid, $job_uuid, $pbs_features) = @_;
c5983223 306
c5983223 307 my $starttime = time ();
09eb196b 308 my $last_time = $starttime;
8825248c 309 my ($last_percent, $last_total, $last_target, $last_zero, $last_transferred) = (-1, 0, 0, 0, 0);
4d159c24 310 my ($transferred, $reused);
c5983223 311
09eb196b
TL
312 my $get_mbps = sub {
313 my ($mb, $delta) = @_;
4d159c24
TL
314 return "0 B/s" if $mb <= 0;
315 my $bw = int(($mb / $delta));
316 return bytes_to_human($bw) . "/s";
09eb196b
TL
317 };
318
3a44897f 319 my $target = 0;
8825248c 320 my $last_reused = 0;
3a44897f
SR
321 my $has_query_bitmap = 0;
322 if (defined($pbs_features) && $pbs_features->{'query-bitmap-info'}) {
323 $has_query_bitmap = 1;
324 my $bitmap_info = mon_cmd($vmid, 'query-pbs-bitmap-info');
325 $self->loginfo("Fast incremental status:");
326 foreach my $info (@$bitmap_info) {
327 my $text = $bitmap_action_to_human->($info);
328 my $drive = $info->{drive};
329 $drive =~ s/^drive-//; # for consistency
330 $self->loginfo("$drive: $text");
331 $target += $info->{dirty};
8825248c 332 $last_reused += $info->{size} - $info->{dirty};
3a44897f
SR
333 }
334 }
335
c5983223 336 while(1) {
09eb196b
TL
337 my $status = mon_cmd($vmid, 'query-backup');
338
c5983223 339 my $total = $status->{total} || 0;
3a44897f 340 $target = $total if !$has_query_bitmap;
c5983223 341 $transferred = $status->{transferred} || 0;
4d159c24 342 $reused = $status->{reused};
0f6c6981 343 my $percent = $target ? int(($transferred * 100)/$target) : 100;
c5983223 344 my $zero = $status->{'zero-bytes'} || 0;
c5983223
DM
345
346 die "got unexpected uuid\n" if !$status->{uuid} || ($status->{uuid} ne $job_uuid);
347
348 my $ctime = time();
349 my $duration = $ctime - $starttime;
350
351 my $rbytes = $transferred - $last_transferred;
8825248c
SR
352 my $wbytes;
353 if ($reused) {
354 # reused includes zero bytes for PBS
355 $wbytes = $rbytes - ($reused - $last_reused);
356 } else {
357 $wbytes = $rbytes - ($zero - $last_zero);
358 }
c5983223
DM
359
360 my $timediff = ($ctime - $last_time) || 1; # fixme
09eb196b
TL
361 my $mbps_read = $get_mbps->($rbytes, $timediff);
362 my $mbps_write = $get_mbps->($wbytes, $timediff);
4d159c24
TL
363 my $target_h = bytes_to_human($target);
364 my $transferred_h = bytes_to_human($transferred);
365
4d159c24
TL
366 my $statusline = "status: $percent% ($transferred_h of $target_h), duration $duration"
367 .", read: $mbps_read, write: $mbps_write";
09eb196b 368
c5983223
DM
369 my $res = $status->{status} || 'unknown';
370 if ($res ne 'active') {
371 $self->loginfo($statusline);
09eb196b
TL
372 if ($res ne 'done') {
373 die (($status->{errmsg} || "unknown error") . "\n") if $res eq 'error';
374 die "got unexpected status '$res'\n";
09eb196b 375 }
6cdb568c
TL
376 $last_target = $target if $target;
377 $last_total = $total if $total;
378 $last_zero = $zero if $zero;
379 $last_transferred = $transferred if $transferred;
c5983223
DM
380 last;
381 }
09eb196b 382 if ($percent != $last_percent && ($timediff > 2)) {
c5983223 383 $self->loginfo($statusline);
09eb196b 384 $last_percent = $percent;
4d159c24 385 $last_target = $target if $target;
c5983223
DM
386 $last_total = $total if $total;
387 $last_zero = $zero if $zero;
388 $last_transferred = $transferred if $transferred;
389 $last_time = $ctime;
8825248c 390 $last_reused = $reused;
c5983223
DM
391 }
392 sleep(1);
393 }
394
395 my $duration = time() - $starttime;
396 if ($transferred && $duration) {
4d159c24 397 my $transferred_h = bytes_to_human($transferred, 2);
09eb196b 398 my $mbps = $get_mbps->($transferred, $duration);
4d159c24
TL
399 if ($reused) {
400 my $reused_h = bytes_to_human($reused, 2);
401 my $reuse_per = int($reused * 100 / $last_total);
91c9f3b0 402 $self->loginfo("backup was done incrementally, reused $reused_h (${reuse_per}%)");
4d159c24 403 }
91c9f3b0 404 $self->loginfo("transferred $transferred_h in $duration seconds ($mbps)");
4d159c24
TL
405 }
406
3a44897f 407 if (!defined($pbs_features) && $last_zero) {
4d159c24
TL
408 my $zero_per = $last_target ? int(($last_zero * 100)/$last_target) : 0;
409 my $zero_h = bytes_to_human($last_zero, 2);
410 $self->loginfo("Backup is sparse: ${zero_per}% ($zero_h) zero data");
c5983223 411 }
b4be9c02
TL
412
413 return {
414 total => $last_total,
415 reused => $reused,
416 };
c5983223
DM
417};
418
419sub archive_pbs {
420 my ($self, $task, $vmid) = @_;
421
1e3baf05 422 my $conffile = "$task->{tmpdir}/qemu-server.conf";
c05f7f3f 423 my $firewall = "$task->{tmpdir}/qemu-server.fw";
1e3baf05
DM
424
425 my $opts = $self->{vzdump}->{opts};
c5983223
DM
426 my $scfg = $opts->{scfg};
427
428 my $starttime = time();
429
c5983223
DM
430 my $server = $scfg->{server};
431 my $datastore = $scfg->{datastore};
432 my $username = $scfg->{username} // 'root@pam';
433 my $fingerprint = $scfg->{fingerprint};
434
435 my $repo = "$username\@$server:$datastore";
436 my $password = PVE::Storage::PBSPlugin::pbs_get_password($scfg, $opts->{storage});
ece74030 437 my $keyfile = PVE::Storage::PBSPlugin::pbs_encryption_key_file_name($scfg, $opts->{storage});
c5983223 438
d11e91d2 439 my $diskcount = scalar(@{$task->{disks}});
c5983223
DM
440 if (PVE::QemuConfig->is_template($self->{vmlist}->{$vmid}) || !$diskcount) {
441 my @pathlist;
b4be9c02 442 # FIXME: accumulate disk sizes to use for backup job (email) log
c5983223
DM
443 foreach my $di (@{$task->{disks}}) {
444 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
445 push @pathlist, "$di->{qmdevice}.img:$di->{path}";
446 } else {
d11e91d2 447 die "implement me (type $di->{type})";
c5983223
DM
448 }
449 }
450
451 if (!$diskcount) {
452 $self->loginfo("backup contains no disks");
453 }
454
455 local $ENV{PBS_PASSWORD} = $password;
77b24c62 456 local $ENV{PBS_FINGERPRINT} = $fingerprint if defined($fingerprint);
c5983223
DM
457 my $cmd = [
458 '/usr/bin/proxmox-backup-client',
459 'backup',
460 '--repository', $repo,
461 '--backup-type', 'vm',
462 '--backup-id', "$vmid",
463 '--backup-time', $task->{backup_time},
d11e91d2 464 ];
c5983223
DM
465
466 push @$cmd, "qemu-server.conf:$conffile";
467 push @$cmd, "fw.conf:$firewall" if -e $firewall;
468 push @$cmd, @pathlist if scalar(@pathlist);
469
470 $self->loginfo("starting template backup");
471 $self->loginfo(join(' ', @$cmd));
472
473 $self->cmd($cmd);
474
475 return;
476 }
477
81dcd479
TL
478 # get list early so we die on unkown drive types before doing anything
479 my $devlist = _get_task_devlist($task);
c5983223 480
0b2f574b 481 $self->enforce_vm_running_for_backup($vmid);
c5983223 482
f6168f1a 483 my $backup_job_uuid;
c5983223
DM
484 eval {
485 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = $SIG{PIPE} = sub {
d11e91d2 486 die "interrupted by signal\n";
c5983223
DM
487 };
488
fb9f512c
SR
489 my $qemu_support = eval { mon_cmd($vmid, "query-proxmox-support") };
490 if (!$qemu_support) {
491 die "PBS backups are not supported by the running QEMU version. Please make "
492 . "sure you've installed the latest version and the VM has been restarted.\n";
493 }
494
cb521f2d 495 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
c5983223 496
d11e91d2
TL
497 my $params = {
498 format => "pbs",
499 'backup-file' => $repo,
500 'backup-id' => "$vmid",
501 'backup-time' => $task->{backup_time},
502 password => $password,
503 devlist => $devlist,
504 'config-file' => $conffile,
c5983223 505 };
d11e91d2
TL
506 $params->{fingerprint} = $fingerprint if defined($fingerprint);
507 $params->{'firewall-file'} = $firewall if -e $firewall;
ece74030
WB
508 if (-e $keyfile) {
509 $self->loginfo("enabling encryption");
510 $params->{keyfile} = $keyfile;
511 $params->{encrypt} = JSON::true;
512 } else {
513 $params->{encrypt} = JSON::false;
514 }
c5983223 515
fb9f512c
SR
516 $params->{'use-dirty-bitmap'} = JSON::true if $qemu_support->{'pbs-dirty-bitmap'};
517
f57666e9
DM
518 $params->{timeout} = 60; # give some time to connect to the backup server
519
d11e91d2 520 my $res = eval { mon_cmd($vmid, "backup", %$params) };
c5983223 521 my $qmperr = $@;
d11e91d2 522 $backup_job_uuid = $res->{UUID} if $res;
c5983223 523
1ece829a
TL
524 if ($fs_frozen) {
525 $self->qga_fs_thaw($vmid);
c5983223
DM
526 }
527
528 die $qmperr if $qmperr;
f6168f1a 529 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
c5983223 530
f6168f1a 531 $self->loginfo("started backup task '$backup_job_uuid'");
c5983223 532
0b2f574b 533 $self->resume_vm_after_job_start($task, $vmid);
c5983223 534
3a44897f 535 my $stat = $query_backup_status_loop->($self, $vmid, $backup_job_uuid, $qemu_support);
2098f2ff 536 $task->{size} = $stat->{total};
c5983223
DM
537 };
538 my $err = $@;
c5983223
DM
539 if ($err) {
540 $self->logerr($err);
0b2f574b 541 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
c5983223 542 }
0b2f574b 543 $self->restore_vm_power_state($vmid);
c5983223
DM
544
545 die $err if $err;
546}
547
02da0c65
TL
548my $fork_compressor_pipe = sub {
549 my ($self, $comp, $outfileno) = @_;
550
551 my @pipefd = POSIX::pipe();
552 my $cpid = fork();
553 die "unable to fork worker - $!" if !defined($cpid) || $cpid < 0;
554 if ($cpid == 0) {
555 eval {
556 POSIX::close($pipefd[1]);
557 # redirect STDIN
558 my $fd = fileno(STDIN);
559 close STDIN;
560 POSIX::close(0) if $fd != 0;
561 die "unable to redirect STDIN - $!"
562 if !open(STDIN, "<&", $pipefd[0]);
563
564 # redirect STDOUT
565 $fd = fileno(STDOUT);
566 close STDOUT;
567 POSIX::close (1) if $fd != 1;
568
569 die "unable to redirect STDOUT - $!"
570 if !open(STDOUT, ">&", $outfileno);
571
572 exec($comp);
573 die "fork compressor '$comp' failed\n";
574 };
575 if (my $err = $@) {
576 $self->logerr($err);
577 POSIX::_exit(1);
578 }
579 POSIX::_exit(0);
580 kill(-9, $$);
581 } else {
582 POSIX::close($pipefd[0]);
583 $outfileno = $pipefd[1];
584 }
585
586 return ($cpid, $outfileno);
587};
588
c5983223
DM
589sub archive_vma {
590 my ($self, $task, $vmid, $filename, $comp) = @_;
591
592 my $conffile = "$task->{tmpdir}/qemu-server.conf";
593 my $firewall = "$task->{tmpdir}/qemu-server.fw";
594
595 my $opts = $self->{vzdump}->{opts};
596
597 my $starttime = time();
1e3baf05 598
91bd6c90
DM
599 my $speed = 0;
600 if ($opts->{bwlimit}) {
874a096e 601 $speed = $opts->{bwlimit}*1024;
91bd6c90 602 }
1e3baf05 603
c82935e9 604 my $diskcount = scalar(@{$task->{disks}});
ffda963f 605 if (PVE::QemuConfig->is_template($self->{vmlist}->{$vmid}) || !$diskcount) {
23b4120b
DM
606 my @pathlist;
607 foreach my $di (@{$task->{disks}}) {
608 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
609 push @pathlist, "$di->{qmdevice}=$di->{path}";
610 } else {
611 die "implement me";
612 }
613 }
614
c82935e9
DM
615 if (!$diskcount) {
616 $self->loginfo("backup contains no disks");
617 }
618
23b4120b
DM
619 my $outcmd;
620 if ($comp) {
874a096e 621 $outcmd = "exec:$comp";
23b4120b 622 } else {
874a096e 623 $outcmd = "exec:cat";
23b4120b
DM
624 }
625
a2fab11a 626 $outcmd .= " > $filename" if !$opts->{stdout};
23b4120b 627
c05f7f3f
WL
628 my $cmd = ['/usr/bin/vma', 'create', '-v', '-c', $conffile];
629 push @$cmd, '-c', $firewall if -e $firewall;
630 push @$cmd, $outcmd, @pathlist;
23b4120b
DM
631
632 $self->loginfo("starting template backup");
633 $self->loginfo(join(' ', @$cmd));
634
635 if ($opts->{stdout}) {
6bb12239 636 $self->cmd($cmd, output => ">&" . fileno($opts->{stdout}));
23b4120b
DM
637 } else {
638 $self->cmd($cmd);
639 }
640
641 return;
642 }
643
81dcd479 644 my $devlist = _get_task_devlist($task);
1e3baf05 645
0b2f574b 646 $self->enforce_vm_running_for_backup($vmid);
91bd6c90
DM
647
648 my $cpid;
d2cc2cbe
DM
649 my $backup_job_uuid;
650
91bd6c90
DM
651 eval {
652 $SIG{INT} = $SIG{TERM} = $SIG{QUIT} = $SIG{HUP} = $SIG{PIPE} = sub {
d11e91d2 653 die "interrupted by signal\n";
91bd6c90
DM
654 };
655
91bd6c90
DM
656 my $outfh;
657 if ($opts->{stdout}) {
658 $outfh = $opts->{stdout};
659 } else {
660 $outfh = IO::File->new($filename, "w") ||
661 die "unable to open file '$filename' - $!\n";
662 }
02da0c65 663 my $outfileno = fileno($outfh);
91bd6c90 664
91bd6c90 665 if ($comp) {
02da0c65 666 ($cpid, $outfileno) = $fork_compressor_pipe->($self, $comp, $outfileno);
91bd6c90
DM
667 }
668
e8705fc5
TL
669 my $qmpclient = PVE::QMPClient->new();
670 my $backup_cb = sub {
671 my ($vmid, $resp) = @_;
672 $backup_job_uuid = $resp->{return}->{UUID};
673 };
674 my $add_fd_cb = sub {
91bd6c90
DM
675 my ($vmid, $resp) = @_;
676
c05f7f3f
WL
677 my $params = {
678 'backup-file' => "/dev/fdname/backup",
679 speed => $speed,
680 'config-file' => $conffile,
681 devlist => $devlist
682 };
c05f7f3f 683 $params->{'firewall-file'} = $firewall if -e $firewall;
d11e91d2 684
c05f7f3f 685 $qmpclient->queue_cmd($vmid, $backup_cb, 'backup', %$params);
91bd6c90
DM
686 };
687
d11e91d2 688 $qmpclient->queue_cmd($vmid, $add_fd_cb, 'getfd', fd => $outfileno, fdname => "backup");
ab6a9a0c 689
cb521f2d 690 my $fs_frozen = $self->qga_fs_freeze($task, $vmid);
874a096e 691
c5983223 692 eval { $qmpclient->queue_execute(30) };
f0f30448 693 my $qmperr = $@;
91bd6c90 694
1ece829a
TL
695 if ($fs_frozen) {
696 $self->qga_fs_thaw($vmid);
ab6a9a0c 697 }
d11e91d2 698
f0f30448 699 die $qmperr if $qmperr;
874a096e 700 die $qmpclient->{errors}->{$vmid} if $qmpclient->{errors}->{$vmid};
91bd6c90
DM
701
702 if ($cpid) {
874a096e 703 POSIX::close($outfileno) == 0 ||
91bd6c90
DM
704 die "close output file handle failed\n";
705 }
706
d2cc2cbe 707 die "got no uuid for backup task\n" if !defined($backup_job_uuid);
91bd6c90 708
d2cc2cbe 709 $self->loginfo("started backup task '$backup_job_uuid'");
91bd6c90 710
0b2f574b 711 $self->resume_vm_after_job_start($task, $vmid);
91bd6c90 712
d2cc2cbe 713 $query_backup_status_loop->($self, $vmid, $backup_job_uuid);
91bd6c90
DM
714 };
715 my $err = $@;
19599cd9 716 if ($err) {
60635a57 717 $self->logerr($err);
0b2f574b 718 $self->mon_backup_cancel($vmid) if defined($backup_job_uuid);
19599cd9
DM
719 }
720
0b2f574b 721 $self->restore_vm_power_state($vmid);
91bd6c90
DM
722
723 if ($err) {
874a096e
DM
724 if ($cpid) {
725 kill(9, $cpid);
91bd6c90
DM
726 waitpid($cpid, 0);
727 }
728 die $err;
729 }
730
731 if ($cpid && (waitpid($cpid, 0) > 0)) {
732 my $stat = $?;
733 my $ec = $stat >> 8;
734 my $signal = $stat & 127;
735 if ($ec || $signal) {
874a096e 736 die "$comp failed - wrong exit status $ec" .
91bd6c90
DM
737 ($signal ? " (signal $signal)\n" : "\n");
738 }
739 }
740}
741
81dcd479
TL
742sub _get_task_devlist {
743 my ($task) = @_;
744
745 my $devlist = '';
746 foreach my $di (@{$task->{disks}}) {
747 if ($di->{type} eq 'block' || $di->{type} eq 'file') {
748 $devlist .= ',' if $devlist;
749 $devlist .= $di->{qmdevice};
750 } else {
751 die "implement me (type '$di->{type}')";
752 }
753 }
754 return $devlist;
755}
756
1ece829a 757sub qga_fs_freeze {
cb521f2d
TL
758 my ($self, $task, $vmid) = @_;
759 return if !$self->{vmlist}->{$vmid}->{agent} || $task->{mode} eq 'stop' || !$self->{vm_was_running};
1ece829a
TL
760
761 if (!PVE::QemuServer::qga_check_running($vmid, 1)) {
762 $self->loginfo("skipping guest-agent 'fs-freeze', agent configured but not running?");
763 return;
764 }
765
766 $self->loginfo("issuing guest-agent 'fs-freeze' command");
767 eval { mon_cmd($vmid, "guest-fsfreeze-freeze") };
768 $self->logerr($@) if $@;
769
770 return 1; # even on mon command error, ensure we always thaw again
771}
772
773# only call if fs_freeze return 1
774sub qga_fs_thaw {
775 my ($self, $vmid) = @_;
776
777 $self->loginfo("issuing guest-agent 'fs-thaw' command");
778 eval { mon_cmd($vmid, "guest-fsfreeze-thaw") };
779 $self->logerr($@) if $@;
780}
781
0b2f574b
TL
782# we need a running QEMU/KVM process for backup, starts a paused (prelaunch)
783# one if VM isn't already running
784sub enforce_vm_running_for_backup {
785 my ($self, $vmid) = @_;
786
787 if (PVE::QemuServer::check_running($vmid)) {
788 $self->{vm_was_running} = 1;
789 return;
790 }
791
792 eval {
793 $self->loginfo("starting kvm to execute backup task");
794 # start with skiplock
0c498cca
FG
795 my $params = {
796 skiplock => 1,
797 paused => 1,
798 };
799 PVE::QemuServer::vm_start($self->{storecfg}, $vmid, $params);
0b2f574b
TL
800 };
801 die $@ if $@;
802}
803
804# resume VM againe once we got in a clear state (stop mode backup of running VM)
805sub resume_vm_after_job_start {
806 my ($self, $task, $vmid) = @_;
807
808 return if !$self->{vm_was_running};
809
810 if (my $stoptime = $task->{vmstoptime}) {
811 my $delay = time() - $task->{vmstoptime};
812 $task->{vmstoptime} = undef; # avoid printing 'online after ..' twice
813 $self->loginfo("resuming VM again after $delay seconds");
814 } else {
815 $self->loginfo("resuming VM again");
816 }
817 mon_cmd($vmid, 'cont');
818}
819
820# stop again if VM was not running before
821sub restore_vm_power_state {
822 my ($self, $vmid) = @_;
823
824 # we always let VMs keep running
825 return if $self->{vm_was_running};
826
827 eval {
828 my $resp = mon_cmd($vmid, 'query-status');
829 my $status = $resp && $resp->{status} ? $resp->{status} : 'unknown';
830 if ($status eq 'prelaunch') {
831 $self->loginfo("stopping kvm after backup task");
832 PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1);
833 } else {
834 $self->loginfo("kvm status changed after backup ('$status') - keep VM running");
835 }
836 };
837 warn $@ if $@;
838}
839
840sub mon_backup_cancel {
841 my ($self, $vmid) = @_;
842
843 $self->loginfo("aborting backup job");
844 eval { mon_cmd($vmid, 'backup-cancel') };
845 $self->logerr($@) if $@;
846}
847
91bd6c90
DM
848sub snapshot {
849 my ($self, $task, $vmid) = @_;
850
851 # nothing to do
1e3baf05
DM
852}
853
854sub cleanup {
855 my ($self, $task, $vmid) = @_;
856
91bd6c90 857 # nothing to do ?
1e3baf05
DM
858}
859
8601;