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