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