]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
schema: fix description of migrate_downtime parameter
[qemu-server.git] / PVE / QemuMigrate.pm
1 package PVE::QemuMigrate;
2
3 use strict;
4 use warnings;
5
6 use IO::File;
7 use IPC::Open2;
8 use Time::HiRes qw( usleep );
9
10 use PVE::Cluster;
11 use PVE::Format qw(render_bytes);
12 use PVE::GuestHelpers qw(safe_boolean_ne safe_string_ne);
13 use PVE::INotify;
14 use PVE::RPCEnvironment;
15 use PVE::Replication;
16 use PVE::ReplicationConfig;
17 use PVE::ReplicationState;
18 use PVE::Storage;
19 use PVE::StorageTunnel;
20 use PVE::Tools;
21 use PVE::Tunnel;
22
23 use PVE::QemuConfig;
24 use PVE::QemuServer::CPUConfig;
25 use PVE::QemuServer::Drive;
26 use PVE::QemuServer::Helpers qw(min_version);
27 use PVE::QemuServer::Machine;
28 use PVE::QemuServer::Monitor qw(mon_cmd);
29 use PVE::QemuServer::Memory qw(get_current_memory);
30 use PVE::QemuServer;
31
32 use PVE::AbstractMigrate;
33 use base qw(PVE::AbstractMigrate);
34
35 # compared against remote end's minimum version
36 our $WS_TUNNEL_VERSION = 2;
37
38 sub fork_tunnel {
39 my ($self, $ssh_forward_info) = @_;
40
41 my $cmd = ['/usr/sbin/qm', 'mtunnel'];
42 my $log = sub {
43 my ($level, $msg) = @_;
44 $self->log($level, $msg);
45 };
46
47 return PVE::Tunnel::fork_ssh_tunnel($self->{rem_ssh}, $cmd, $ssh_forward_info, $log);
48 }
49
50 sub fork_websocket_tunnel {
51 my ($self, $storages, $bridges) = @_;
52
53 my $remote = $self->{opts}->{remote};
54 my $conn = $remote->{conn};
55
56 my $log = sub {
57 my ($level, $msg) = @_;
58 $self->log($level, $msg);
59 };
60
61 my $websocket_url = "https://$conn->{host}:$conn->{port}/api2/json/nodes/$self->{node}/qemu/$remote->{vmid}/mtunnelwebsocket";
62 my $url = "/nodes/$self->{node}/qemu/$remote->{vmid}/mtunnel";
63
64 my $tunnel_params = {
65 url => $websocket_url,
66 };
67
68 my $storage_list = join(',', keys %$storages);
69 my $bridge_list = join(',', keys %$bridges);
70
71 my $req_params = {
72 storages => $storage_list,
73 bridges => $bridge_list,
74 };
75
76 return PVE::Tunnel::fork_websocket_tunnel($conn, $url, $req_params, $tunnel_params, $log);
77 }
78
79 # tunnel_info:
80 # proto: unix (secure) or tcp (insecure/legacy compat)
81 # addr: IP or UNIX socket path
82 # port: optional TCP port
83 # unix_sockets: additional UNIX socket paths to forward
84 sub start_remote_tunnel {
85 my ($self, $tunnel_info) = @_;
86
87 my $nodename = PVE::INotify::nodename();
88 my $migration_type = $self->{opts}->{migration_type};
89
90 if ($migration_type eq 'secure') {
91
92 if ($tunnel_info->{proto} eq 'unix') {
93 my $ssh_forward_info = [];
94
95 my $unix_sockets = [ keys %{$tunnel_info->{unix_sockets}} ];
96 push @$unix_sockets, $tunnel_info->{addr};
97 for my $sock (@$unix_sockets) {
98 push @$ssh_forward_info, "$sock:$sock";
99 unlink $sock;
100 }
101
102 $self->{tunnel} = $self->fork_tunnel($ssh_forward_info);
103
104 my $unix_socket_try = 0; # wait for the socket to become ready
105 while ($unix_socket_try <= 100) {
106 $unix_socket_try++;
107 my $available = 0;
108 foreach my $sock (@$unix_sockets) {
109 if (-S $sock) {
110 $available++;
111 }
112 }
113
114 if ($available == @$unix_sockets) {
115 last;
116 }
117
118 usleep(50000);
119 }
120 if ($unix_socket_try > 100) {
121 $self->{errors} = 1;
122 PVE::Tunnel::finish_tunnel($self->{tunnel});
123 die "Timeout, migration socket $tunnel_info->{addr} did not get ready";
124 }
125 $self->{tunnel}->{unix_sockets} = $unix_sockets if (@$unix_sockets);
126
127 } elsif ($tunnel_info->{proto} eq 'tcp') {
128 my $ssh_forward_info = [];
129 if ($tunnel_info->{addr} eq "localhost") {
130 # for backwards compatibility with older qemu-server versions
131 my $pfamily = PVE::Tools::get_host_address_family($nodename);
132 my $lport = PVE::Tools::next_migrate_port($pfamily);
133 push @$ssh_forward_info, "$lport:localhost:$tunnel_info->{port}";
134 }
135
136 $self->{tunnel} = $self->fork_tunnel($ssh_forward_info);
137
138 } else {
139 die "unsupported protocol in migration URI: $tunnel_info->{proto}\n";
140 }
141 } else {
142 #fork tunnel for insecure migration, to send faster commands like resume
143 $self->{tunnel} = $self->fork_tunnel();
144 }
145 }
146
147 sub lock_vm {
148 my ($self, $vmid, $code, @param) = @_;
149
150 return PVE::QemuConfig->lock_config($vmid, $code, @param);
151 }
152
153 sub target_storage_check_available {
154 my ($self, $storecfg, $targetsid, $volid) = @_;
155
156 if (!$self->{opts}->{remote}) {
157 # check if storage is available on target node
158 my $target_scfg = PVE::Storage::storage_check_enabled(
159 $storecfg,
160 $targetsid,
161 $self->{node},
162 );
163 my ($vtype) = PVE::Storage::parse_volname($storecfg, $volid);
164 die "$volid: content type '$vtype' is not available on storage '$targetsid'\n"
165 if !$target_scfg->{content}->{$vtype};
166 }
167 }
168
169 sub prepare {
170 my ($self, $vmid) = @_;
171
172 my $online = $self->{opts}->{online};
173
174 my $storecfg = $self->{storecfg} = PVE::Storage::config();
175
176 # test if VM exists
177 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
178
179 my $version = PVE::QemuServer::Helpers::get_node_pvecfg_version($self->{node});
180 my $cloudinit_config = $conf->{cloudinit};
181
182 if (
183 PVE::QemuConfig->has_cloudinit($conf) && defined($cloudinit_config)
184 && scalar(keys %$cloudinit_config) > 0
185 && !PVE::QemuServer::Helpers::pvecfg_min_version($version, 7, 2, 13)
186 ) {
187 die "target node is too old (manager <= 7.2-13) and doesn't support new cloudinit section\n";
188 }
189
190 my $repl_conf = PVE::ReplicationConfig->new();
191 $self->{replication_jobcfg} = $repl_conf->find_local_replication_job($vmid, $self->{node});
192 $self->{is_replicated} = $repl_conf->check_for_existing_jobs($vmid, 1);
193
194 if ($self->{replication_jobcfg} && defined($self->{replication_jobcfg}->{remove_job})) {
195 die "refusing to migrate replicated VM whose replication job is marked for removal\n";
196 }
197
198 PVE::QemuConfig->check_lock($conf);
199
200 my $running = 0;
201 if (my $pid = PVE::QemuServer::check_running($vmid)) {
202 die "can't migrate running VM without --online\n" if !$online;
203 $running = $pid;
204
205 if ($self->{is_replicated} && !$self->{replication_jobcfg}) {
206 if ($self->{opts}->{force}) {
207 $self->log('warn', "WARNING: Node '$self->{node}' is not a replication target. Existing " .
208 "replication jobs will fail after migration!\n");
209 } else {
210 die "Cannot live-migrate replicated VM to node '$self->{node}' - not a replication " .
211 "target. Use 'force' to override.\n";
212 }
213 }
214
215 $self->{forcemachine} = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
216
217 # To support custom CPU types, we keep QEMU's "-cpu" parameter intact.
218 # Since the parameter itself contains no reference to a custom model,
219 # this makes migration independent of changes to "cpu-models.conf".
220 if ($conf->{cpu}) {
221 my $cpuconf = PVE::JSONSchema::parse_property_string('pve-cpu-conf', $conf->{cpu});
222 if ($cpuconf && PVE::QemuServer::CPUConfig::is_custom_model($cpuconf->{cputype})) {
223 $self->{forcecpu} = PVE::QemuServer::CPUConfig::get_cpu_from_running_vm($pid);
224 }
225 }
226
227 # Do not treat a suspended VM as paused, as it might wake up
228 # during migration and remain paused after migration finishes.
229 $self->{vm_was_paused} = 1 if PVE::QemuServer::vm_is_paused($vmid, 0);
230 }
231
232 my ($loc_res, $mapped_res, $missing_mappings_by_node) = PVE::QemuServer::check_local_resources($conf, 1);
233 my $blocking_resources = [];
234 for my $res ($loc_res->@*) {
235 if (!grep($res, $mapped_res->@*)) {
236 push $blocking_resources->@*, $res;
237 }
238 }
239 if (scalar($blocking_resources->@*)) {
240 if ($self->{running} || !$self->{opts}->{force}) {
241 die "can't migrate VM which uses local devices: " . join(", ", $blocking_resources->@*) . "\n";
242 } else {
243 $self->log('info', "migrating VM which uses local devices");
244 }
245 }
246
247 if (scalar($mapped_res->@*)) {
248 my $missing_mappings = $missing_mappings_by_node->{$self->{node}};
249 if ($running) {
250 die "can't migrate running VM which uses mapped devices: " . join(", ", $mapped_res->@*) . "\n";
251 } elsif (scalar($missing_mappings->@*)) {
252 die "can't migrate to '$self->{node}': missing mapped devices " . join(", ", $missing_mappings->@*) . "\n";
253 } else {
254 $self->log('info', "migrating VM which uses mapped local devices");
255 }
256 }
257
258 my $vga = PVE::QemuServer::parse_vga($conf->{vga});
259 if ($running && $vga->{'clipboard'} && $vga->{'clipboard'} eq 'vnc') {
260 die "VMs with 'clipboard' set to 'vnc' are not live migratable!\n";
261 }
262
263 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
264
265 my $storages = {};
266 foreach my $volid (@$vollist) {
267 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
268
269 # check if storage is available on source node
270 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
271
272 my $targetsid = $sid;
273 # NOTE: local ignores shared mappings, remote maps them
274 if (!$scfg->{shared} || $self->{opts}->{remote}) {
275 $targetsid = PVE::JSONSchema::map_id($self->{opts}->{storagemap}, $sid);
276 }
277
278 $storages->{$targetsid} = 1;
279
280 $self->target_storage_check_available($storecfg, $targetsid, $volid);
281
282 if ($scfg->{shared}) {
283 # PVE::Storage::activate_storage checks this for non-shared storages
284 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
285 warn "Used shared storage '$sid' is not online on source node!\n"
286 if !$plugin->check_connection($sid, $scfg);
287 }
288 }
289
290 if ($self->{opts}->{remote}) {
291 # test & establish websocket connection
292 my $bridges = map_bridges($conf, $self->{opts}->{bridgemap}, 1);
293 my $tunnel = $self->fork_websocket_tunnel($storages, $bridges);
294 my $min_version = $tunnel->{version} - $tunnel->{age};
295 $self->log('info', "local WS tunnel version: $WS_TUNNEL_VERSION");
296 $self->log('info', "remote WS tunnel version: $tunnel->{version}");
297 $self->log('info', "minimum required WS tunnel version: $min_version");
298 die "Remote tunnel endpoint not compatible, upgrade required\n"
299 if $WS_TUNNEL_VERSION < $min_version;
300 die "Remote tunnel endpoint too old, upgrade required\n"
301 if $WS_TUNNEL_VERSION > $tunnel->{version};
302
303 print "websocket tunnel started\n";
304 $self->{tunnel} = $tunnel;
305 } else {
306 # test ssh connection
307 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
308 eval { $self->cmd_quiet($cmd); };
309 die "Can't connect to destination address using public key\n" if $@;
310 }
311
312 return $running;
313 }
314
315 sub scan_local_volumes {
316 my ($self, $vmid) = @_;
317
318 my $conf = $self->{vmconf};
319
320 # local volumes which have been copied
321 # and their old_id => new_id pairs
322 $self->{volume_map} = {};
323 $self->{local_volumes} = {};
324
325 my $storecfg = $self->{storecfg};
326 eval {
327 # found local volumes and their origin
328 my $local_volumes = $self->{local_volumes};
329 my $local_volumes_errors = {};
330 my $other_errors = [];
331 my $abort = 0;
332 my $path_to_volid = {};
333
334 my $log_error = sub {
335 my ($msg, $volid) = @_;
336
337 if (defined($volid)) {
338 $local_volumes_errors->{$volid} = $msg;
339 } else {
340 push @$other_errors, $msg;
341 }
342 $abort = 1;
343 };
344
345 my $replicatable_volumes = !$self->{replication_jobcfg} ? {}
346 : PVE::QemuConfig->get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
347 foreach my $volid (keys %{$replicatable_volumes}) {
348 $local_volumes->{$volid}->{replicated} = 1;
349 }
350
351 my $test_volid = sub {
352 my ($volid, $attr) = @_;
353
354 if ($volid =~ m|^/|) {
355 return if $attr->{shared};
356 $local_volumes->{$volid}->{ref} = 'config';
357 die "local file/device\n";
358 }
359
360 my $snaprefs = $attr->{referenced_in_snapshot};
361
362 if ($attr->{cdrom}) {
363 if ($volid eq 'cdrom') {
364 my $msg = "can't migrate local cdrom drive";
365 if (defined($snaprefs) && !$attr->{is_attached}) {
366 my $snapnames = join(', ', sort keys %$snaprefs);
367 $msg .= " (referenced in snapshot - $snapnames)";
368 }
369 &$log_error("$msg\n");
370 return;
371 }
372 return if $volid eq 'none';
373 }
374
375 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
376
377 # check if storage is available on both nodes
378 my $scfg = PVE::Storage::storage_check_enabled($storecfg, $sid);
379
380 my $targetsid = $sid;
381 # NOTE: local ignores shared mappings, remote maps them
382 if (!$scfg->{shared} || $self->{opts}->{remote}) {
383 $targetsid = PVE::JSONSchema::map_id($self->{opts}->{storagemap}, $sid);
384 }
385
386 $self->target_storage_check_available($storecfg, $targetsid, $volid);
387 return if $scfg->{shared} && !$self->{opts}->{remote};
388
389 $local_volumes->{$volid}->{ref} = 'pending' if $attr->{referenced_in_pending};
390 $local_volumes->{$volid}->{ref} = 'snapshot' if $attr->{referenced_in_snapshot};
391 $local_volumes->{$volid}->{ref} = 'unused' if $attr->{is_unused};
392 $local_volumes->{$volid}->{ref} = 'attached' if $attr->{is_attached};
393 $local_volumes->{$volid}->{ref} = 'generated' if $attr->{is_tpmstate};
394
395 $local_volumes->{$volid}->{bwlimit} = $self->get_bwlimit($sid, $targetsid);
396 $local_volumes->{$volid}->{targetsid} = $targetsid;
397
398 $local_volumes->{$volid}->@{qw(size format)} = PVE::Storage::volume_size_info($storecfg, $volid);
399
400 $local_volumes->{$volid}->{is_vmstate} = $attr->{is_vmstate} ? 1 : 0;
401
402 $local_volumes->{$volid}->{drivename} = $attr->{drivename}
403 if $attr->{drivename};
404
405 # If with_snapshots is not set for storage migrate, it tries to use
406 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
407 # back to qcow2 is currently not possible.
408 $local_volumes->{$volid}->{snapshots} = ($local_volumes->{$volid}->{format} =~ /^(?:qcow2|vmdk)$/);
409
410 if ($attr->{cdrom}) {
411 if ($volid =~ /vm-\d+-cloudinit/) {
412 $local_volumes->{$volid}->{ref} = 'generated';
413 return;
414 }
415 die "local cdrom image\n";
416 }
417
418 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
419
420 die "owned by other VM (owner = VM $owner)\n"
421 if !$owner || ($owner != $vmid);
422
423 $path_to_volid->{$path}->{$volid} = 1;
424
425 return if $attr->{is_vmstate};
426
427 if (defined($snaprefs)) {
428 $local_volumes->{$volid}->{snapshots} = 1;
429
430 # we cannot migrate shapshots on local storage
431 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
432
433 die "online storage migration not possible if non-replicated snapshot exists\n"
434 if $self->{running} && !$local_volumes->{$volid}->{replicated};
435
436 die "remote migration with snapshots not supported yet\n" if $self->{opts}->{remote};
437
438 if (!($scfg->{type} eq 'zfspool'
439 || ($scfg->{type} eq 'btrfs' && $local_volumes->{$volid}->{format} eq 'raw')
440 || $local_volumes->{$volid}->{format} eq 'qcow2'
441 )) {
442 die "non-migratable snapshot exists\n";
443 }
444 }
445
446 die "referenced by linked clone(s)\n"
447 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
448 };
449
450 PVE::QemuServer::foreach_volid($conf, sub {
451 my ($volid, $attr) = @_;
452 eval { $test_volid->($volid, $attr); };
453 if (my $err = $@) {
454 &$log_error($err, $volid);
455 }
456 });
457
458 for my $path (keys %$path_to_volid) {
459 my @volids = keys $path_to_volid->{$path}->%*;
460 die "detected not supported aliased volumes: '" . join("', '", @volids) . "'\n"
461 if (scalar(@volids) > 1);
462 }
463
464 foreach my $vol (sort keys %$local_volumes) {
465 my $type = $replicatable_volumes->{$vol} ? 'local, replicated' : 'local';
466 my $ref = $local_volumes->{$vol}->{ref};
467 if ($ref eq 'attached') {
468 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
469 if $self->{running} && !$self->{opts}->{"with-local-disks"};
470 $self->log('info', "found $type disk '$vol' (attached)\n");
471 } elsif ($ref eq 'unused') {
472 $self->log('info', "found $type disk '$vol' (unused)\n");
473 } elsif ($ref eq 'snapshot') {
474 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
475 } elsif ($ref eq 'pending') {
476 $self->log('info', "found $type disk '$vol' (pending change)\n");
477 } elsif ($ref eq 'generated') {
478 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
479 } else {
480 $self->log('info', "found $type disk '$vol'\n");
481 }
482 }
483
484 foreach my $vol (sort keys %$local_volumes_errors) {
485 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
486 }
487 foreach my $err (@$other_errors) {
488 $self->log('warn', "$err");
489 }
490
491 if ($abort) {
492 die "can't migrate VM - check log\n";
493 }
494
495 # additional checks for local storage
496 foreach my $volid (keys %$local_volumes) {
497 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
498 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
499
500 my $migratable = $scfg->{type} =~ /^(?:dir|btrfs|zfspool|lvmthin|lvm)$/;
501
502 # TODO: what is this even here for?
503 $migratable = 1 if $self->{opts}->{remote};
504
505 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
506 if !$migratable;
507
508 # image is a linked clone on local storage, se we can't migrate.
509 if (my $basename = (PVE::Storage::parse_volname($storecfg, $volid))[3]) {
510 die "can't migrate '$volid' as it's a clone of '$basename'";
511 }
512 }
513
514 foreach my $volid (sort keys %$local_volumes) {
515 my $ref = $local_volumes->{$volid}->{ref};
516 if ($self->{running} && $ref eq 'attached') {
517 $local_volumes->{$volid}->{migration_mode} = 'online';
518 } elsif ($self->{running} && $ref eq 'generated') {
519 # offline migrate the cloud-init ISO and don't regenerate on VM start
520 #
521 # tpmstate will also be offline migrated first, and in case of
522 # live migration then updated by QEMU/swtpm if necessary
523 $local_volumes->{$volid}->{migration_mode} = 'offline';
524 } else {
525 $local_volumes->{$volid}->{migration_mode} = 'offline';
526 }
527 }
528 };
529 die "Problem found while scanning volumes - $@" if $@;
530 }
531
532 sub handle_replication {
533 my ($self, $vmid) = @_;
534
535 my $conf = $self->{vmconf};
536 my $local_volumes = $self->{local_volumes};
537
538 return if !$self->{replication_jobcfg};
539
540 die "can't migrate VM with replicated volumes to remote cluster/node\n"
541 if $self->{opts}->{remote};
542
543 if ($self->{running}) {
544
545 my $version = PVE::QemuServer::kvm_user_version();
546 if (!min_version($version, 4, 2)) {
547 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
548 }
549
550 my @live_replicatable_volumes = $self->filter_local_volumes('online', 1);
551 foreach my $volid (@live_replicatable_volumes) {
552 my $drive = $local_volumes->{$volid}->{drivename};
553 die "internal error - no drive for '$volid'\n" if !defined($drive);
554
555 my $bitmap = "repl_$drive";
556
557 # start tracking before replication to get full delta + a few duplicates
558 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
559 mon_cmd($vmid, 'block-dirty-bitmap-add', node => "drive-$drive", name => $bitmap);
560
561 # other info comes from target node in phase 2
562 $self->{target_drive}->{$drive}->{bitmap} = $bitmap;
563 }
564 }
565 $self->log('info', "replicating disk images");
566
567 my $start_time = time();
568 my $logfunc = sub { $self->log('info', shift) };
569 my $actual_replicated_volumes = PVE::Replication::run_replication(
570 'PVE::QemuConfig', $self->{replication_jobcfg}, $start_time, $start_time, $logfunc);
571
572 # extra safety check
573 my @replicated_volumes = $self->filter_local_volumes(undef, 1);
574 foreach my $volid (@replicated_volumes) {
575 die "expected volume '$volid' to get replicated, but it wasn't\n"
576 if !$actual_replicated_volumes->{$volid};
577 }
578 }
579
580 sub config_update_local_disksizes {
581 my ($self) = @_;
582
583 my $conf = $self->{vmconf};
584 my $local_volumes = $self->{local_volumes};
585
586 PVE::QemuConfig->foreach_volume($conf, sub {
587 my ($key, $drive) = @_;
588 # skip special disks, will be handled later
589 return if $key eq 'efidisk0';
590 return if $key eq 'tpmstate0';
591
592 my $volid = $drive->{file};
593 return if !defined($local_volumes->{$volid}); # only update sizes for local volumes
594
595 my ($updated, $msg) = PVE::QemuServer::Drive::update_disksize($drive, $local_volumes->{$volid}->{size});
596 if (defined($updated)) {
597 $conf->{$key} = PVE::QemuServer::print_drive($updated);
598 $self->log('info', "drive '$key': $msg");
599 }
600 });
601
602 # we want to set the efidisk size in the config to the size of the
603 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
604 if (defined($conf->{efidisk0})) {
605 PVE::QemuServer::update_efidisk_size($conf);
606 }
607
608 # TPM state might have an irregular filesize, to avoid problems on transfer
609 # we always assume the static size of 4M to allocate on the target
610 if (defined($conf->{tpmstate0})) {
611 PVE::QemuServer::update_tpmstate_size($conf);
612 }
613 }
614
615 sub filter_local_volumes {
616 my ($self, $migration_mode, $replicated) = @_;
617
618 my $volumes = $self->{local_volumes};
619 my @filtered_volids;
620
621 foreach my $volid (sort keys %{$volumes}) {
622 next if defined($migration_mode) && safe_string_ne($volumes->{$volid}->{migration_mode}, $migration_mode);
623 next if defined($replicated) && safe_boolean_ne($volumes->{$volid}->{replicated}, $replicated);
624 push @filtered_volids, $volid;
625 }
626
627 return @filtered_volids;
628 }
629
630 sub sync_offline_local_volumes {
631 my ($self) = @_;
632
633 my $local_volumes = $self->{local_volumes};
634 my @volids = $self->filter_local_volumes('offline', 0);
635
636 my $storecfg = $self->{storecfg};
637 my $opts = $self->{opts};
638
639 $self->log('info', "copying local disk images") if scalar(@volids);
640
641 foreach my $volid (@volids) {
642 my $new_volid;
643
644 my $opts = $self->{opts};
645 if ($opts->{remote}) {
646 my $log = sub {
647 my ($level, $msg) = @_;
648 $self->log($level, $msg);
649 };
650
651 $new_volid = PVE::StorageTunnel::storage_migrate(
652 $self->{tunnel},
653 $storecfg,
654 $volid,
655 $self->{vmid},
656 $opts->{remote}->{vmid},
657 $local_volumes->{$volid},
658 $log,
659 );
660 } else {
661 my $targetsid = $local_volumes->{$volid}->{targetsid};
662
663 my $bwlimit = $local_volumes->{$volid}->{bwlimit};
664 $bwlimit = $bwlimit * 1024 if defined($bwlimit); # storage_migrate uses bps
665
666 my $storage_migrate_opts = {
667 'ratelimit_bps' => $bwlimit,
668 'insecure' => $opts->{migration_type} eq 'insecure',
669 'with_snapshots' => $local_volumes->{$volid}->{snapshots},
670 'allow_rename' => !$local_volumes->{$volid}->{is_vmstate},
671 };
672
673 my $logfunc = sub { $self->log('info', $_[0]); };
674 $new_volid = eval {
675 PVE::Storage::storage_migrate(
676 $storecfg,
677 $volid,
678 $self->{ssh_info},
679 $targetsid,
680 $storage_migrate_opts,
681 $logfunc,
682 );
683 };
684 if (my $err = $@) {
685 die "storage migration for '$volid' to storage '$targetsid' failed - $err\n";
686 }
687 }
688
689 $self->{volume_map}->{$volid} = $new_volid;
690 $self->log('info', "volume '$volid' is '$new_volid' on the target\n");
691
692 eval { PVE::Storage::deactivate_volumes($storecfg, [$volid]); };
693 if (my $err = $@) {
694 $self->log('warn', $err);
695 }
696 }
697 }
698
699 sub cleanup_remotedisks {
700 my ($self) = @_;
701
702 if ($self->{opts}->{remote}) {
703 PVE::Tunnel::finish_tunnel($self->{tunnel}, 1);
704 delete $self->{tunnel};
705 return;
706 }
707
708 my $local_volumes = $self->{local_volumes};
709
710 foreach my $volid (values %{$self->{volume_map}}) {
711 # don't clean up replicated disks!
712 next if $local_volumes->{$volid}->{replicated};
713
714 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
715
716 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
717
718 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
719 if (my $err = $@) {
720 $self->log('err', $err);
721 $self->{errors} = 1;
722 }
723 }
724 }
725
726 sub cleanup_bitmaps {
727 my ($self) = @_;
728 foreach my $drive (keys %{$self->{target_drive}}) {
729 my $bitmap = $self->{target_drive}->{$drive}->{bitmap};
730 next if !$bitmap;
731 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
732 mon_cmd($self->{vmid}, 'block-dirty-bitmap-remove', node => "drive-$drive", name => $bitmap);
733 }
734 }
735
736 sub phase1 {
737 my ($self, $vmid) = @_;
738
739 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
740
741 my $conf = $self->{vmconf};
742
743 # set migrate lock in config file
744 $conf->{lock} = 'migrate';
745 PVE::QemuConfig->write_config($vmid, $conf);
746
747 $self->scan_local_volumes($vmid);
748
749 # fix disk sizes to match their actual size and write changes,
750 # so that the target allocates the correct volumes
751 $self->config_update_local_disksizes();
752 PVE::QemuConfig->write_config($vmid, $conf);
753
754 $self->handle_replication($vmid);
755
756 $self->sync_offline_local_volumes();
757 $self->phase1_remote($vmid) if $self->{opts}->{remote};
758 };
759
760 sub map_bridges {
761 my ($conf, $map, $scan_only) = @_;
762
763 my $bridges = {};
764
765 foreach my $opt (keys %$conf) {
766 next if $opt !~ m/^net\d+$/;
767
768 next if !$conf->{$opt};
769 my $d = PVE::QemuServer::parse_net($conf->{$opt});
770 next if !$d || !$d->{bridge};
771
772 my $target_bridge = PVE::JSONSchema::map_id($map, $d->{bridge});
773 $bridges->{$target_bridge}->{$opt} = $d->{bridge};
774
775 next if $scan_only;
776
777 $d->{bridge} = $target_bridge;
778 $conf->{$opt} = PVE::QemuServer::print_net($d);
779 }
780
781 return $bridges;
782 }
783
784 sub phase1_remote {
785 my ($self, $vmid) = @_;
786
787 my $remote_conf = PVE::QemuConfig->load_config($vmid);
788 PVE::QemuConfig->update_volume_ids($remote_conf, $self->{volume_map});
789
790 my $bridges = map_bridges($remote_conf, $self->{opts}->{bridgemap});
791 for my $target (keys $bridges->%*) {
792 for my $nic (keys $bridges->{$target}->%*) {
793 $self->log('info', "mapped: $nic from $bridges->{$target}->{$nic} to $target");
794 }
795 }
796
797 my @online_local_volumes = $self->filter_local_volumes('online');
798
799 my $storage_map = $self->{opts}->{storagemap};
800 $self->{nbd} = {};
801 PVE::QemuConfig->foreach_volume($remote_conf, sub {
802 my ($ds, $drive) = @_;
803
804 # TODO eject CDROM?
805 return if PVE::QemuServer::drive_is_cdrom($drive);
806
807 my $volid = $drive->{file};
808 return if !$volid;
809
810 return if !grep { $_ eq $volid} @online_local_volumes;
811
812 my ($storeid, $volname) = PVE::Storage::parse_volume_id($volid);
813 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
814 my $source_format = PVE::QemuServer::qemu_img_format($scfg, $volname);
815
816 # set by target cluster
817 my $oldvolid = delete $drive->{file};
818 delete $drive->{format};
819
820 my $targetsid = PVE::JSONSchema::map_id($storage_map, $storeid);
821
822 my $params = {
823 format => $source_format,
824 storage => $targetsid,
825 drive => $drive,
826 };
827
828 $self->log('info', "Allocating volume for drive '$ds' on remote storage '$targetsid'..");
829 my $res = PVE::Tunnel::write_tunnel($self->{tunnel}, 600, 'disk', $params);
830
831 $self->log('info', "volume '$oldvolid' is '$res->{volid}' on the target\n");
832 $remote_conf->{$ds} = $res->{drivestr};
833 $self->{nbd}->{$ds} = $res;
834 });
835
836 my $conf_str = PVE::QemuServer::write_vm_config("remote", $remote_conf);
837
838 # TODO expose in PVE::Firewall?
839 my $vm_fw_conf_path = "/etc/pve/firewall/$vmid.fw";
840 my $fw_conf_str;
841 $fw_conf_str = PVE::Tools::file_get_contents($vm_fw_conf_path)
842 if -e $vm_fw_conf_path;
843 my $params = {
844 conf => $conf_str,
845 'firewall-config' => $fw_conf_str,
846 };
847
848 PVE::Tunnel::write_tunnel($self->{tunnel}, 10, 'config', $params);
849 }
850
851 sub phase1_cleanup {
852 my ($self, $vmid, $err) = @_;
853
854 $self->log('info', "aborting phase 1 - cleanup resources");
855
856 my $conf = $self->{vmconf};
857 delete $conf->{lock};
858 eval { PVE::QemuConfig->write_config($vmid, $conf) };
859 if (my $err = $@) {
860 $self->log('err', $err);
861 }
862
863 eval { $self->cleanup_remotedisks() };
864 if (my $err = $@) {
865 $self->log('err', $err);
866 }
867
868 eval { $self->cleanup_bitmaps() };
869 if (my $err =$@) {
870 $self->log('err', $err);
871 }
872 }
873
874 sub phase2_start_local_cluster {
875 my ($self, $vmid, $params) = @_;
876
877 my $conf = $self->{vmconf};
878 my $local_volumes = $self->{local_volumes};
879 my @online_local_volumes = $self->filter_local_volumes('online');
880
881 my $start = $params->{start_params};
882 my $migrate = $params->{migrate_opts};
883
884 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
885
886 my $tunnel_info = {};
887
888 ## start on remote node
889 my $cmd = [@{$self->{rem_ssh}}];
890
891 push @$cmd, 'qm', 'start', $vmid;
892
893 if ($start->{skiplock}) {
894 push @$cmd, '--skiplock';
895 }
896
897 push @$cmd, '--migratedfrom', $migrate->{migratedfrom};
898
899 push @$cmd, '--migration_type', $migrate->{type};
900
901 push @$cmd, '--migration_network', $migrate->{network}
902 if $migrate->{network};
903
904 push @$cmd, '--stateuri', $start->{statefile};
905
906 if ($start->{forcemachine}) {
907 push @$cmd, '--machine', $start->{forcemachine};
908 }
909
910 if ($start->{forcecpu}) {
911 push @$cmd, '--force-cpu', $start->{forcecpu};
912 }
913
914 if ($self->{storage_migration}) {
915 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
916 }
917
918 my $spice_port;
919 my $input = "nbd_protocol_version: $migrate->{nbd_proto_version}\n";
920
921 my @offline_local_volumes = $self->filter_local_volumes('offline');
922 for my $volid (@offline_local_volumes) {
923 my $drivename = $local_volumes->{$volid}->{drivename};
924 next if !$drivename || !$conf->{$drivename};
925
926 my $new_volid = $self->{volume_map}->{$volid};
927 next if !$new_volid || $volid eq $new_volid;
928
929 # FIXME PVE 8.x only use offline_volume variant once all targets can handle it
930 if ($drivename eq 'tpmstate0') {
931 $input .= "$drivename: $new_volid\n"
932 } else {
933 $input .= "offline_volume: $drivename: $new_volid\n"
934 }
935 }
936
937 $input .= "spice_ticket: $migrate->{spice_ticket}\n" if $migrate->{spice_ticket};
938
939 my @online_replicated_volumes = $self->filter_local_volumes('online', 1);
940 foreach my $volid (@online_replicated_volumes) {
941 $input .= "replicated_volume: $volid\n";
942 }
943
944 my $handle_storage_migration_listens = sub {
945 my ($drive_key, $drivestr, $nbd_uri) = @_;
946
947 $self->{stopnbd} = 1;
948 $self->{target_drive}->{$drive_key}->{drivestr} = $drivestr;
949 $self->{target_drive}->{$drive_key}->{nbd_uri} = $nbd_uri;
950
951 my $source_drive = PVE::QemuServer::parse_drive($drive_key, $conf->{$drive_key});
952 my $target_drive = PVE::QemuServer::parse_drive($drive_key, $drivestr);
953 my $source_volid = $source_drive->{file};
954 my $target_volid = $target_drive->{file};
955
956 $self->{volume_map}->{$source_volid} = $target_volid;
957 $self->log('info', "volume '$source_volid' is '$target_volid' on the target\n");
958 };
959
960 my $target_replicated_volumes = {};
961
962 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
963 # instead we pipe it through STDIN
964 my $exitcode = PVE::Tools::run_command($cmd, input => $input, outfunc => sub {
965 my $line = shift;
966
967 if ($line =~ m/^migration listens on (tcp):(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
968 $tunnel_info->{addr} = $2;
969 $tunnel_info->{port} = int($3);
970 $tunnel_info->{proto} = $1;
971 }
972 elsif ($line =~ m!^migration listens on (unix):(/run/qemu-server/(\d+)\.migrate)$!) {
973 $tunnel_info->{addr} = $2;
974 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $3;
975 $tunnel_info->{proto} = $1;
976 }
977 elsif ($line =~ m/^migration listens on port (\d+)$/) {
978 $tunnel_info->{addr} = "localhost";
979 $tunnel_info->{port} = int($1);
980 $tunnel_info->{proto} = "tcp";
981 }
982 elsif ($line =~ m/^spice listens on port (\d+)$/) {
983 $spice_port = int($1);
984 }
985 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
986 my $drivestr = $4;
987 my $nbd_uri = "nbd:$1:$2:exportname=$3";
988 my $targetdrive = $3;
989 $targetdrive =~ s/drive-//g;
990
991 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
992 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
993 my $drivestr = $4;
994 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
995 my $nbd_unix_addr = $1;
996 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
997 my $targetdrive = $3;
998 $targetdrive =~ s/drive-//g;
999
1000 $handle_storage_migration_listens->($targetdrive, $drivestr, $nbd_uri);
1001 $tunnel_info->{unix_sockets}->{$nbd_unix_addr} = 1;
1002 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
1003 my $drive = $1;
1004 my $volid = $2;
1005 $target_replicated_volumes->{$volid} = $drive;
1006 } elsif ($line =~ m/^QEMU: (.*)$/) {
1007 $self->log('info', "[$self->{node}] $1\n");
1008 }
1009 }, errfunc => sub {
1010 my $line = shift;
1011 $self->log('info', "[$self->{node}] $line");
1012 }, noerr => 1);
1013
1014 die "remote command failed with exit code $exitcode\n" if $exitcode;
1015
1016 die "unable to detect remote migration address\n" if !$tunnel_info->{addr} || !$tunnel_info->{proto};
1017
1018 if (scalar(keys %$target_replicated_volumes) != scalar(@online_replicated_volumes)) {
1019 die "number of replicated disks on source and target node do not match - target node too old?\n"
1020 }
1021
1022 return ($tunnel_info, $spice_port);
1023 }
1024
1025 sub phase2_start_remote_cluster {
1026 my ($self, $vmid, $params) = @_;
1027
1028 die "insecure migration to remote cluster not implemented\n"
1029 if $params->{migrate_opts}->{type} ne 'websocket';
1030
1031 my $remote_vmid = $self->{opts}->{remote}->{vmid};
1032
1033 # like regular start but with some overhead accounted for
1034 my $memory = get_current_memory($self->{vmconf}->{memory});
1035 my $timeout = PVE::QemuServer::Helpers::config_aware_timeout($self->{vmconf}, $memory) + 10;
1036
1037 my $res = PVE::Tunnel::write_tunnel($self->{tunnel}, $timeout, "start", $params);
1038
1039 foreach my $drive (keys %{$res->{drives}}) {
1040 $self->{stopnbd} = 1;
1041 $self->{target_drive}->{$drive}->{drivestr} = $res->{drives}->{$drive}->{drivestr};
1042 my $nbd_uri = $res->{drives}->{$drive}->{nbd_uri};
1043 die "unexpected NBD uri for '$drive': $nbd_uri\n"
1044 if $nbd_uri !~ s!/run/qemu-server/$remote_vmid\_!/run/qemu-server/$vmid\_!;
1045
1046 $self->{target_drive}->{$drive}->{nbd_uri} = $nbd_uri;
1047 }
1048
1049 return ($res->{migrate}, $res->{spice_port});
1050 }
1051
1052 sub phase2 {
1053 my ($self, $vmid) = @_;
1054
1055 my $conf = $self->{vmconf};
1056 my $local_volumes = $self->{local_volumes};
1057
1058 # version > 0 for unix socket support
1059 my $nbd_protocol_version = 1;
1060
1061 my $spice_ticket;
1062 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
1063 my $res = mon_cmd($vmid, 'query-spice');
1064 $spice_ticket = $res->{ticket};
1065 }
1066
1067 my $migration_type = $self->{opts}->{migration_type};
1068 my $state_uri = $migration_type eq 'insecure' ? 'tcp' : 'unix';
1069
1070 my $params = {
1071 start_params => {
1072 statefile => $state_uri,
1073 forcemachine => $self->{forcemachine},
1074 forcecpu => $self->{forcecpu},
1075 skiplock => 1,
1076 },
1077 migrate_opts => {
1078 spice_ticket => $spice_ticket,
1079 type => $migration_type,
1080 network => $self->{opts}->{migration_network},
1081 storagemap => $self->{opts}->{storagemap},
1082 migratedfrom => PVE::INotify::nodename(),
1083 nbd_proto_version => $nbd_protocol_version,
1084 nbd => $self->{nbd},
1085 },
1086 };
1087
1088 my ($tunnel_info, $spice_port);
1089
1090 my @online_local_volumes = $self->filter_local_volumes('online');
1091 $self->{storage_migration} = 1 if scalar(@online_local_volumes);
1092
1093 if (my $remote = $self->{opts}->{remote}) {
1094 my $remote_vmid = $remote->{vmid};
1095 $params->{migrate_opts}->{remote_node} = $self->{node};
1096 ($tunnel_info, $spice_port) = $self->phase2_start_remote_cluster($vmid, $params);
1097 die "only UNIX sockets are supported for remote migration\n"
1098 if $tunnel_info->{proto} ne 'unix';
1099
1100 my $remote_socket = $tunnel_info->{addr};
1101 my $local_socket = $remote_socket;
1102 $local_socket =~ s/$remote_vmid/$vmid/g;
1103 $tunnel_info->{addr} = $local_socket;
1104
1105 $self->log('info', "Setting up tunnel for '$local_socket'");
1106 PVE::Tunnel::forward_unix_socket($self->{tunnel}, $local_socket, $remote_socket);
1107
1108 foreach my $remote_socket (@{$tunnel_info->{unix_sockets}}) {
1109 my $local_socket = $remote_socket;
1110 $local_socket =~ s/$remote_vmid/$vmid/g;
1111 next if $self->{tunnel}->{forwarded}->{$local_socket};
1112 $self->log('info', "Setting up tunnel for '$local_socket'");
1113 PVE::Tunnel::forward_unix_socket($self->{tunnel}, $local_socket, $remote_socket);
1114 }
1115 } else {
1116 ($tunnel_info, $spice_port) = $self->phase2_start_local_cluster($vmid, $params);
1117
1118 $self->log('info', "start remote tunnel");
1119 $self->start_remote_tunnel($tunnel_info);
1120 }
1121
1122 my $migrate_uri = "$tunnel_info->{proto}:$tunnel_info->{addr}";
1123 $migrate_uri .= ":$tunnel_info->{port}"
1124 if defined($tunnel_info->{port});
1125
1126 if ($self->{storage_migration}) {
1127 $self->{storage_migration_jobs} = {};
1128 $self->log('info', "starting storage migration");
1129
1130 die "The number of local disks does not match between the source and the destination.\n"
1131 if (scalar(keys %{$self->{target_drive}}) != scalar(@online_local_volumes));
1132 foreach my $drive (keys %{$self->{target_drive}}){
1133 my $target = $self->{target_drive}->{$drive};
1134 my $nbd_uri = $target->{nbd_uri};
1135
1136 my $source_drive = PVE::QemuServer::parse_drive($drive, $conf->{$drive});
1137 my $source_volid = $source_drive->{file};
1138
1139 my $bwlimit = $self->{local_volumes}->{$source_volid}->{bwlimit};
1140 my $bitmap = $target->{bitmap};
1141
1142 $self->log('info', "$drive: start migration to $nbd_uri");
1143 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 'skip', undef, $bwlimit, $bitmap);
1144 }
1145 }
1146
1147 $self->log('info', "starting online/live migration on $migrate_uri");
1148 $self->{livemigration} = 1;
1149
1150 # load_defaults
1151 my $defaults = PVE::QemuServer::load_defaults();
1152
1153 $self->log('info', "set migration capabilities");
1154 eval { PVE::QemuServer::set_migration_caps($vmid) };
1155 warn $@ if $@;
1156
1157 my $qemu_migrate_params = {};
1158
1159 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
1160 # migrate_speed parameter in qm.conf - take the lower of the two.
1161 my $bwlimit = $self->get_bwlimit();
1162
1163 my $migrate_speed = $conf->{migrate_speed} // 0;
1164 $migrate_speed *= 1024; # migrate_speed is in MB/s, bwlimit in KB/s
1165
1166 if ($bwlimit && $migrate_speed) {
1167 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
1168 } else {
1169 $migrate_speed ||= $bwlimit;
1170 }
1171 $migrate_speed ||= ($defaults->{migrate_speed} || 0) * 1024;
1172
1173 if ($migrate_speed) {
1174 $migrate_speed *= 1024; # qmp takes migrate_speed in B/s.
1175 $self->log('info', "migration speed limit: ". render_bytes($migrate_speed, 1) ."/s");
1176 } else {
1177 # always set migrate speed as QEMU default to 128 MiBps == 1 Gbps, use 16 GiBps == 128 Gbps
1178 $migrate_speed = (16 << 30);
1179 }
1180 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
1181
1182 my $migrate_downtime = $defaults->{migrate_downtime};
1183 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
1184 # migrate-set-parameters expects limit in ms
1185 $migrate_downtime *= 1000;
1186 $self->log('info', "migration downtime limit: $migrate_downtime ms");
1187 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
1188
1189 # set cachesize to 10% of the total memory
1190 my $memory = get_current_memory($conf->{memory});
1191 my $cachesize = int($memory * 1048576 / 10);
1192 $cachesize = round_powerof2($cachesize);
1193
1194 $self->log('info', "migration cachesize: " . render_bytes($cachesize, 1));
1195 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
1196
1197 $self->log('info', "set migration parameters");
1198 eval {
1199 mon_cmd($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
1200 };
1201 $self->log('info', "migrate-set-parameters error: $@") if $@;
1202
1203 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && !$self->{opts}->{remote}) {
1204 my $rpcenv = PVE::RPCEnvironment::get();
1205 my $authuser = $rpcenv->get_user();
1206
1207 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
1208
1209 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
1210 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
1211
1212 $self->log('info', "spice client_migrate_info");
1213
1214 eval {
1215 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
1216 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
1217 'cert-subject' => $subject);
1218 };
1219 $self->log('info', "client_migrate_info error: $@") if $@;
1220
1221 }
1222
1223 my $start = time();
1224
1225 $self->log('info', "start migrate command to $migrate_uri");
1226 eval {
1227 mon_cmd($vmid, "migrate", uri => $migrate_uri);
1228 };
1229 my $merr = $@;
1230 $self->log('info', "migrate uri => $migrate_uri failed: $merr") if $merr;
1231
1232 my $last_mem_transferred = 0;
1233 my $usleep = 1000000;
1234 my $i = 0;
1235 my $err_count = 0;
1236 my $lastrem = undef;
1237 my $downtimecounter = 0;
1238 while (1) {
1239 $i++;
1240 my $avglstat = $last_mem_transferred ? $last_mem_transferred / $i : 0;
1241
1242 usleep($usleep);
1243
1244 my $stat = eval { mon_cmd($vmid, "query-migrate") };
1245 if (my $err = $@) {
1246 $err_count++;
1247 warn "query migrate failed: $err\n";
1248 $self->log('info', "query migrate failed: $err");
1249 if ($err_count <= 5) {
1250 usleep(1_000_000);
1251 next;
1252 }
1253 die "too many query migrate failures - aborting\n";
1254 }
1255
1256 my $status = $stat->{status};
1257 if (defined($status) && $status =~ m/^(setup)$/im) {
1258 sleep(1);
1259 next;
1260 }
1261
1262 if (!defined($status) || $status !~ m/^(active|completed|failed|cancelled)$/im) {
1263 die $merr if $merr;
1264 die "unable to parse migration status '$status' - aborting\n";
1265 }
1266 $merr = undef;
1267 $err_count = 0;
1268
1269 my $memstat = $stat->{ram};
1270
1271 if ($status eq 'completed') {
1272 my $delay = time() - $start;
1273 if ($delay > 0) {
1274 my $total = $memstat->{total} || 0;
1275 my $avg_speed = render_bytes($total / $delay, 1);
1276 my $downtime = $stat->{downtime} || 0;
1277 $self->log('info', "average migration speed: $avg_speed/s - downtime $downtime ms");
1278 }
1279 }
1280
1281 if ($status eq 'failed' || $status eq 'cancelled') {
1282 my $message = $stat->{'error-desc'} ? "$status - $stat->{'error-desc'}" : $status;
1283 $self->log('info', "migration status error: $message");
1284 die "aborting\n"
1285 }
1286
1287 if ($status ne 'active') {
1288 $self->log('info', "migration status: $status");
1289 last;
1290 }
1291
1292 if ($memstat->{transferred} ne $last_mem_transferred) {
1293 my $trans = $memstat->{transferred} || 0;
1294 my $rem = $memstat->{remaining} || 0;
1295 my $total = $memstat->{total} || 0;
1296 my $speed = ($memstat->{'pages-per-second'} // 0) * ($memstat->{'page-size'} // 0);
1297 my $dirty_rate = ($memstat->{'dirty-pages-rate'} // 0) * ($memstat->{'page-size'} // 0);
1298
1299 # reduce sleep if remainig memory is lower than the average transfer speed
1300 $usleep = 100_000 if $avglstat && $rem < $avglstat;
1301
1302 # also reduce loggin if we poll more frequent
1303 my $should_log = $usleep > 100_000 ? 1 : ($i % 10) == 0;
1304
1305 my $total_h = render_bytes($total, 1);
1306 my $transferred_h = render_bytes($trans, 1);
1307 my $speed_h = render_bytes($speed, 1);
1308
1309 my $progress = "transferred $transferred_h of $total_h VM-state, ${speed_h}/s";
1310
1311 if ($dirty_rate > $speed) {
1312 my $dirty_rate_h = render_bytes($dirty_rate, 1);
1313 $progress .= ", VM dirties lots of memory: $dirty_rate_h/s";
1314 }
1315
1316 $self->log('info', "migration $status, $progress") if $should_log;
1317
1318 my $xbzrle = $stat->{"xbzrle-cache"} || {};
1319 my ($xbzrlebytes, $xbzrlepages) = $xbzrle->@{'bytes', 'pages'};
1320 if ($xbzrlebytes || $xbzrlepages) {
1321 my $bytes_h = render_bytes($xbzrlebytes, 1);
1322
1323 my $msg = "send updates to $xbzrlepages pages in $bytes_h encoded memory";
1324
1325 $msg .= sprintf(", cache-miss %.2f%%", $xbzrle->{'cache-miss-rate'} * 100)
1326 if $xbzrle->{'cache-miss-rate'};
1327
1328 $msg .= ", overflow $xbzrle->{overflow}" if $xbzrle->{overflow};
1329
1330 $self->log('info', "xbzrle: $msg") if $should_log;
1331 }
1332
1333 if (($lastrem && $rem > $lastrem) || ($rem == 0)) {
1334 $downtimecounter++;
1335 }
1336 $lastrem = $rem;
1337
1338 if ($downtimecounter > 5) {
1339 $downtimecounter = 0;
1340 $migrate_downtime *= 2;
1341 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1342 eval {
1343 # migrate-set-parameters does not touch values not
1344 # specified, so this only changes downtime-limit
1345 mon_cmd($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1346 };
1347 $self->log('info', "migrate-set-parameters error: $@") if $@;
1348 }
1349 }
1350
1351 $last_mem_transferred = $memstat->{transferred};
1352 }
1353
1354 if ($self->{storage_migration}) {
1355 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1356 # to avoid it trying to re-establish it. We are in blockjob ready state,
1357 # thus, this command changes to it to blockjob complete (see qapi docs)
1358 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}, 'cancel'); };
1359 if (my $err = $@) {
1360 die "Failed to complete storage migration: $err\n";
1361 }
1362 }
1363 }
1364
1365 sub phase2_cleanup {
1366 my ($self, $vmid, $err) = @_;
1367
1368 return if !$self->{errors};
1369 $self->{phase2errors} = 1;
1370
1371 $self->log('info', "aborting phase 2 - cleanup resources");
1372
1373 $self->log('info', "migrate_cancel");
1374 eval {
1375 mon_cmd($vmid, "migrate_cancel");
1376 };
1377 $self->log('info', "migrate_cancel error: $@") if $@;
1378
1379 my $vm_status = eval {
1380 mon_cmd($vmid, 'query-status')->{status} or die "no 'status' in result\n";
1381 };
1382 $self->log('err', "query-status error: $@") if $@;
1383
1384 # Can end up in POSTMIGRATE state if failure occurred after convergence. Try going back to
1385 # original state. Unfortunately, direct transition from POSTMIGRATE to PAUSED is not possible.
1386 if ($vm_status && $vm_status eq 'postmigrate') {
1387 if (!$self->{vm_was_paused}) {
1388 eval { mon_cmd($vmid, 'cont'); };
1389 $self->log('err', "resuming VM failed: $@") if $@;
1390 } else {
1391 $self->log('err', "VM was paused, but ended in postmigrate state");
1392 }
1393 }
1394
1395 my $conf = $self->{vmconf};
1396 delete $conf->{lock};
1397 eval { PVE::QemuConfig->write_config($vmid, $conf) };
1398 if (my $err = $@) {
1399 $self->log('err', $err);
1400 }
1401
1402 # cleanup ressources on target host
1403 if ($self->{storage_migration}) {
1404 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1405 if (my $err = $@) {
1406 $self->log('err', $err);
1407 }
1408 }
1409
1410 eval { $self->cleanup_bitmaps() };
1411 if (my $err =$@) {
1412 $self->log('err', $err);
1413 }
1414
1415 my $nodename = PVE::INotify::nodename();
1416
1417 if ($self->{tunnel} && $self->{tunnel}->{version} >= 2) {
1418 PVE::Tunnel::write_tunnel($self->{tunnel}, 10, 'stop');
1419 } else {
1420 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1421 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1422 if (my $err = $@) {
1423 $self->log('err', $err);
1424 $self->{errors} = 1;
1425 }
1426 }
1427
1428 # cleanup after stopping, otherwise disks might be in-use by target VM!
1429 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1430 if (my $err = $@) {
1431 $self->log('err', $err);
1432 }
1433
1434
1435 if ($self->{tunnel}) {
1436 eval { PVE::Tunnel::finish_tunnel($self->{tunnel}); };
1437 if (my $err = $@) {
1438 $self->log('err', $err);
1439 $self->{errors} = 1;
1440 }
1441 }
1442 }
1443
1444 sub phase3 {
1445 my ($self, $vmid) = @_;
1446
1447 return;
1448 }
1449
1450 sub phase3_cleanup {
1451 my ($self, $vmid, $err) = @_;
1452
1453 my $conf = $self->{vmconf};
1454 return if $self->{phase2errors};
1455
1456 my $tunnel = $self->{tunnel};
1457
1458 my $sourcevollist = PVE::QemuServer::get_vm_volumes($conf);
1459
1460 if ($self->{volume_map} && !$self->{opts}->{remote}) {
1461 my $target_drives = $self->{target_drive};
1462
1463 # FIXME: for NBD storage migration we now only update the volid, and
1464 # not the full drivestr from the target node. Workaround that until we
1465 # got some real rescan, to avoid things like wrong format in the drive
1466 delete $conf->{$_} for keys %$target_drives;
1467 PVE::QemuConfig->update_volume_ids($conf, $self->{volume_map});
1468
1469 for my $drive (keys %$target_drives) {
1470 $conf->{$drive} = $target_drives->{$drive}->{drivestr};
1471 }
1472 PVE::QemuConfig->write_config($vmid, $conf);
1473 }
1474
1475 # transfer replication state before move config
1476 if (!$self->{opts}->{remote}) {
1477 $self->transfer_replication_state() if $self->{is_replicated};
1478 PVE::QemuConfig->move_config_to_node($vmid, $self->{node});
1479 $self->switch_replication_job_target() if $self->{is_replicated};
1480 }
1481
1482 if ($self->{livemigration}) {
1483 if ($self->{stopnbd}) {
1484 $self->log('info', "stopping NBD storage migration server on target.");
1485 # stop nbd server on remote vm - requirement for resume since 2.9
1486 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 2) {
1487 eval {
1488 PVE::Tunnel::write_tunnel($tunnel, 30, 'nbdstop');
1489 };
1490 if (my $err = $@) {
1491 $self->log('err', $err);
1492 $self->{errors} = 1;
1493 }
1494 } else {
1495 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
1496
1497 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1498 if (my $err = $@) {
1499 $self->log('err', $err);
1500 $self->{errors} = 1;
1501 }
1502 }
1503 }
1504
1505 # deletes local FDB entries if learning is disabled, they'll be re-added on target on resume
1506 PVE::QemuServer::del_nets_bridge_fdb($conf, $vmid);
1507
1508 if (!$self->{vm_was_paused}) {
1509 # config moved and nbd server stopped - now we can resume vm on target
1510 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
1511 my $cmd = $tunnel->{version} == 1 ? "resume $vmid" : "resume";
1512 eval {
1513 PVE::Tunnel::write_tunnel($tunnel, 30, $cmd);
1514 };
1515 if (my $err = $@) {
1516 $self->log('err', $err);
1517 $self->{errors} = 1;
1518 }
1519 } else {
1520 # nocheck in case target node hasn't processed the config move/rename yet
1521 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1522 my $logf = sub {
1523 my $line = shift;
1524 $self->log('err', $line);
1525 };
1526 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
1527 if (my $err = $@) {
1528 $self->log('err', $err);
1529 $self->{errors} = 1;
1530 }
1531 }
1532 }
1533
1534 if (
1535 $self->{storage_migration}
1536 && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks}
1537 && $self->{running}
1538 ) {
1539 if (!$self->{vm_was_paused}) {
1540 $self->log('info', "issuing guest fstrim");
1541 if ($self->{opts}->{remote}) {
1542 PVE::Tunnel::write_tunnel($self->{tunnel}, 600, 'fstrim');
1543 } else {
1544 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1545 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1546 if (my $err = $@) {
1547 $self->log('err', "fstrim failed - $err");
1548 $self->{errors} = 1;
1549 }
1550 }
1551 } else {
1552 $self->log('info', "skipping guest fstrim, because VM is paused");
1553 }
1554 }
1555 }
1556
1557 # close tunnel on successful migration, on error phase2_cleanup closed it
1558 if ($tunnel && $tunnel->{version} == 1) {
1559 eval { PVE::Tunnel::finish_tunnel($tunnel); };
1560 if (my $err = $@) {
1561 $self->log('err', $err);
1562 $self->{errors} = 1;
1563 }
1564 $tunnel = undef;
1565 delete $self->{tunnel};
1566 }
1567
1568 eval {
1569 my $timer = 0;
1570 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1571 $self->log('info', "Waiting for spice server migration");
1572 while (1) {
1573 my $res = mon_cmd($vmid, 'query-spice');
1574 last if int($res->{'migrated'}) == 1;
1575 last if $timer > 50;
1576 $timer ++;
1577 usleep(200000);
1578 }
1579 }
1580 };
1581
1582 # always stop local VM with nocheck, since config is moved already
1583 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1584 if (my $err = $@) {
1585 $self->log('err', "stopping vm failed - $err");
1586 $self->{errors} = 1;
1587 }
1588
1589 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1590 eval {
1591 PVE::Storage::deactivate_volumes($self->{storecfg}, $sourcevollist);
1592 };
1593 if (my $err = $@) {
1594 $self->log('err', $err);
1595 $self->{errors} = 1;
1596 }
1597
1598 my @not_replicated_volumes = $self->filter_local_volumes(undef, 0);
1599
1600 # destroy local copies
1601 foreach my $volid (@not_replicated_volumes) {
1602 # remote is cleaned up below
1603 next if $self->{opts}->{remote};
1604
1605 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1606 if (my $err = $@) {
1607 $self->log('err', "removing local copy of '$volid' failed - $err");
1608 $self->{errors} = 1;
1609 last if $err =~ /^interrupted by signal$/;
1610 }
1611 }
1612
1613 # clear migrate lock
1614 if ($tunnel && $tunnel->{version} >= 2) {
1615 PVE::Tunnel::write_tunnel($tunnel, 10, "unlock");
1616
1617 PVE::Tunnel::finish_tunnel($tunnel);
1618 } else {
1619 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1620 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1621 }
1622
1623 if ($self->{opts}->{remote} && $self->{opts}->{delete}) {
1624 eval { PVE::QemuServer::destroy_vm($self->{storecfg}, $vmid, 1, undef, 0) };
1625 warn "Failed to remove source VM - $@\n" if $@;
1626 }
1627 }
1628
1629 sub final_cleanup {
1630 my ($self, $vmid) = @_;
1631
1632 # nothing to do
1633 }
1634
1635 sub round_powerof2 {
1636 return 1 if $_[0] < 2;
1637 return 2 << int(log($_[0]-1)/log(2));
1638 }
1639
1640 1;