]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
2925b90d14320db71d8c812921879d24906fb38c
[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 POSIX qw( WNOHANG );
9 use Time::HiRes qw( usleep );
10
11 use PVE::Cluster;
12 use PVE::INotify;
13 use PVE::RPCEnvironment;
14 use PVE::Replication;
15 use PVE::ReplicationConfig;
16 use PVE::ReplicationState;
17 use PVE::Storage;
18 use PVE::Tools;
19
20 use PVE::QemuConfig;
21 use PVE::QemuServer::CPUConfig;
22 use PVE::QemuServer::Drive;
23 use PVE::QemuServer::Helpers qw(min_version);
24 use PVE::QemuServer::Machine;
25 use PVE::QemuServer::Monitor qw(mon_cmd);
26 use PVE::QemuServer;
27
28 use PVE::AbstractMigrate;
29 use base qw(PVE::AbstractMigrate);
30
31 sub fork_command_pipe {
32 my ($self, $cmd) = @_;
33
34 my $reader = IO::File->new();
35 my $writer = IO::File->new();
36
37 my $orig_pid = $$;
38
39 my $cpid;
40
41 eval { $cpid = open2($reader, $writer, @$cmd); };
42
43 my $err = $@;
44
45 # catch exec errors
46 if ($orig_pid != $$) {
47 $self->log('err', "can't fork command pipe\n");
48 POSIX::_exit(1);
49 kill('KILL', $$);
50 }
51
52 die $err if $err;
53
54 return { writer => $writer, reader => $reader, pid => $cpid };
55 }
56
57 sub finish_command_pipe {
58 my ($self, $cmdpipe, $timeout) = @_;
59
60 my $cpid = $cmdpipe->{pid};
61 return if !defined($cpid);
62
63 my $writer = $cmdpipe->{writer};
64 my $reader = $cmdpipe->{reader};
65
66 $writer->close();
67 $reader->close();
68
69 my $collect_child_process = sub {
70 my $res = waitpid($cpid, WNOHANG);
71 if (defined($res) && ($res == $cpid)) {
72 delete $cmdpipe->{cpid};
73 return 1;
74 } else {
75 return 0;
76 }
77 };
78
79 if ($timeout) {
80 for (my $i = 0; $i < $timeout; $i++) {
81 return if &$collect_child_process();
82 sleep(1);
83 }
84 }
85
86 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
87 kill(15, $cpid);
88
89 # wait again
90 for (my $i = 0; $i < 10; $i++) {
91 return if &$collect_child_process();
92 sleep(1);
93 }
94
95 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
96 kill 9, $cpid;
97 sleep 1;
98
99 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
100 if !&$collect_child_process();
101 }
102
103 sub read_tunnel {
104 my ($self, $tunnel, $timeout) = @_;
105
106 $timeout = 60 if !defined($timeout);
107
108 my $reader = $tunnel->{reader};
109
110 my $output;
111 eval {
112 PVE::Tools::run_with_timeout($timeout, sub { $output = <$reader>; });
113 };
114 die "reading from tunnel failed: $@\n" if $@;
115
116 chomp $output;
117
118 return $output;
119 }
120
121 sub write_tunnel {
122 my ($self, $tunnel, $timeout, $command) = @_;
123
124 $timeout = 60 if !defined($timeout);
125
126 my $writer = $tunnel->{writer};
127
128 eval {
129 PVE::Tools::run_with_timeout($timeout, sub {
130 print $writer "$command\n";
131 $writer->flush();
132 });
133 };
134 die "writing to tunnel failed: $@\n" if $@;
135
136 if ($tunnel->{version} && $tunnel->{version} >= 1) {
137 my $res = eval { $self->read_tunnel($tunnel, 10); };
138 die "no reply to command '$command': $@\n" if $@;
139
140 if ($res eq 'OK') {
141 return;
142 } else {
143 die "tunnel replied '$res' to command '$command'\n";
144 }
145 }
146 }
147
148 sub fork_tunnel {
149 my ($self, $tunnel_addr) = @_;
150
151 my @localtunnelinfo = ();
152 foreach my $addr (@$tunnel_addr) {
153 push @localtunnelinfo, '-L', $addr;
154 }
155
156 my $cmd = [@{$self->{rem_ssh}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, '/usr/sbin/qm', 'mtunnel' ];
157
158 my $tunnel = $self->fork_command_pipe($cmd);
159
160 eval {
161 my $helo = $self->read_tunnel($tunnel, 60);
162 die "no reply\n" if !$helo;
163 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
164 die "got strange reply from mtunnel ('$helo')\n"
165 if $helo !~ m/^tunnel online$/;
166 };
167 my $err = $@;
168
169 eval {
170 my $ver = $self->read_tunnel($tunnel, 10);
171 if ($ver =~ /^ver (\d+)$/) {
172 $tunnel->{version} = $1;
173 $self->log('info', "ssh tunnel $ver\n");
174 } else {
175 $err = "received invalid tunnel version string '$ver'\n" if !$err;
176 }
177 };
178
179 if ($err) {
180 $self->finish_command_pipe($tunnel);
181 die "can't open migration tunnel - $err";
182 }
183 return $tunnel;
184 }
185
186 sub finish_tunnel {
187 my ($self, $tunnel) = @_;
188
189 eval { $self->write_tunnel($tunnel, 30, 'quit'); };
190 my $err = $@;
191
192 $self->finish_command_pipe($tunnel, 30);
193
194 if ($tunnel->{sock_addr}) {
195 # ssh does not clean up on local host
196 my $cmd = ['rm', '-f', @{$tunnel->{sock_addr}}]; #
197 PVE::Tools::run_command($cmd);
198
199 # .. and just to be sure check on remote side
200 unshift @{$cmd}, @{$self->{rem_ssh}};
201 PVE::Tools::run_command($cmd);
202 }
203
204 die $err if $err;
205 }
206
207 sub lock_vm {
208 my ($self, $vmid, $code, @param) = @_;
209
210 return PVE::QemuConfig->lock_config($vmid, $code, @param);
211 }
212
213 sub prepare {
214 my ($self, $vmid) = @_;
215
216 my $online = $self->{opts}->{online};
217
218 $self->{storecfg} = PVE::Storage::config();
219
220 # test if VM exists
221 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
222
223 PVE::QemuConfig->check_lock($conf);
224
225 my $running = 0;
226 if (my $pid = PVE::QemuServer::check_running($vmid)) {
227 die "can't migrate running VM without --online\n" if !$online;
228 $running = $pid;
229
230 $self->{forcemachine} = PVE::QemuServer::Machine::qemu_machine_pxe($vmid, $conf);
231
232 # To support custom CPU types, we keep QEMU's "-cpu" parameter intact.
233 # Since the parameter itself contains no reference to a custom model,
234 # this makes migration independent of changes to "cpu-models.conf".
235 if ($conf->{cpu}) {
236 my $cpuconf = PVE::QemuServer::CPUConfig::parse_cpu_conf_basic($conf->{cpu});
237 if ($cpuconf && PVE::QemuServer::CPUConfig::is_custom_model($cpuconf->{cputype})) {
238 $self->{forcecpu} = PVE::QemuServer::CPUConfig::get_cpu_from_running_vm($pid);
239 }
240 }
241 }
242
243 my $loc_res = PVE::QemuServer::check_local_resources($conf, 1);
244 if (scalar @$loc_res) {
245 if ($self->{running} || !$self->{opts}->{force}) {
246 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
247 } else {
248 $self->log('info', "migrating VM which uses local devices");
249 }
250 }
251
252 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
253
254 my $need_activate = [];
255 foreach my $volid (@$vollist) {
256 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
257
258 # check if storage is available on both nodes
259 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $sid);
260
261 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
262 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
263
264 if ($scfg->{shared}) {
265 # PVE::Storage::activate_storage checks this for non-shared storages
266 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
267 warn "Used shared storage '$sid' is not online on source node!\n"
268 if !$plugin->check_connection($sid, $scfg);
269 } else {
270 # only activate if not shared
271 next if ($volid =~ m/vm-\d+-cloudinit/);
272 push @$need_activate, $volid;
273 }
274 }
275
276 # activate volumes
277 PVE::Storage::activate_volumes($self->{storecfg}, $need_activate);
278
279 # test ssh connection
280 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
281 eval { $self->cmd_quiet($cmd); };
282 die "Can't connect to destination address using public key\n" if $@;
283
284 return $running;
285 }
286
287 sub sync_disks {
288 my ($self, $vmid) = @_;
289
290 my $conf = $self->{vmconf};
291
292 # local volumes which have been copied
293 $self->{volumes} = [];
294
295 my $storecfg = $self->{storecfg};
296 eval {
297
298 # found local volumes and their origin
299 my $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};
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);
323
324 next if @{$dl->{$storeid}} == 0;
325
326 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $storeid);
327 # check if storage is available on target node
328 PVE::Storage::storage_check_node($storecfg, $targetsid, $self->{node});
329
330 # grandfather in existing mismatches
331 if ($targetsid ne $storeid) {
332 my $target_scfg = PVE::Storage::storage_config($storecfg, $targetsid);
333 die "content type 'images' is not available on storage '$targetsid'\n"
334 if !$target_scfg->{content}->{images};
335 }
336
337 PVE::Storage::foreach_volid($dl, sub {
338 my ($volid, $sid, $volinfo) = @_;
339
340 $local_volumes->{$volid}->{ref} = 'storage';
341
342 # If with_snapshots is not set for storage migrate, it tries to use
343 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
344 # back to qcow2 is currently not possible.
345 $local_volumes->{$volid}->{snapshots} = ($volinfo->{format} =~ /^(?:qcow2|vmdk)$/);
346 $local_volumes->{$volid}->{format} = $volinfo->{format};
347 });
348 }
349
350 my $rep_cfg = PVE::ReplicationConfig->new();
351 my $replication_jobcfg = $rep_cfg->find_local_replication_job($vmid, $self->{node});
352 my $replicatable_volumes = !$replication_jobcfg ? {}
353 : PVE::QemuConfig->get_replicatable_volumes($storecfg, $vmid, $conf, 0, 1);
354
355 my $test_volid = sub {
356 my ($volid, $attr) = @_;
357
358 if ($volid =~ m|^/|) {
359 return if $attr->{shared};
360 $local_volumes->{$volid}->{ref} = 'config';
361 die "local file/device\n";
362 }
363
364 my $snaprefs = $attr->{referenced_in_snapshot};
365
366 if ($attr->{cdrom}) {
367 if ($volid eq 'cdrom') {
368 my $msg = "can't migrate local cdrom drive";
369 if (defined($snaprefs) && !$attr->{referenced_in_config}) {
370 my $snapnames = join(', ', sort keys %$snaprefs);
371 $msg .= " (referenced in snapshot - $snapnames)";
372 }
373 &$log_error("$msg\n");
374 return;
375 }
376 return if $volid eq 'none';
377 }
378
379 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
380
381 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $sid);
382 # check if storage is available on both nodes
383 my $scfg = PVE::Storage::storage_check_node($storecfg, $sid);
384 PVE::Storage::storage_check_node($storecfg, $targetsid, $self->{node});
385
386 return if $scfg->{shared};
387
388 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config} ? 'config' : 'snapshot';
389
390 if ($attr->{cdrom}) {
391 if ($volid =~ /vm-\d+-cloudinit/) {
392 $local_volumes->{$volid}->{ref} = 'generated';
393 return;
394 }
395 die "local cdrom image\n";
396 }
397
398 my ($path, $owner) = PVE::Storage::path($storecfg, $volid);
399
400 die "owned by other VM (owner = VM $owner)\n"
401 if !$owner || ($owner != $vmid);
402
403 if (defined($snaprefs)) {
404 $local_volumes->{$volid}->{snapshots} = 1;
405
406 # we cannot migrate shapshots on local storage
407 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
408
409 die "online storage migration not possible if snapshot exists\n" if $self->{running};
410 if (!($scfg->{type} eq 'zfspool' || $local_volumes->{$volid}->{format} eq 'qcow2')) {
411 die "non-migratable snapshot exists\n";
412 }
413 }
414
415 die "referenced by linked clone(s)\n"
416 if PVE::Storage::volume_is_base_and_used($storecfg, $volid);
417 };
418
419 PVE::QemuServer::foreach_volid($conf, sub {
420 my ($volid, $attr) = @_;
421 eval { $test_volid->($volid, $attr); };
422 if (my $err = $@) {
423 &$log_error($err, $volid);
424 }
425 });
426
427 foreach my $vol (sort keys %$local_volumes) {
428 my $type = $replicatable_volumes->{$vol} ? 'local, replicated' : 'local';
429 my $ref = $local_volumes->{$vol}->{ref};
430 if ($ref eq 'storage') {
431 $self->log('info', "found $type disk '$vol' (via storage)\n");
432 } elsif ($ref eq 'config') {
433 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
434 if $self->{running} && !$self->{opts}->{"with-local-disks"};
435 $self->log('info', "found $type disk '$vol' (in current VM config)\n");
436 } elsif ($ref eq 'snapshot') {
437 $self->log('info', "found $type disk '$vol' (referenced by snapshot(s))\n");
438 } elsif ($ref eq 'generated') {
439 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
440 } else {
441 $self->log('info', "found $type disk '$vol'\n");
442 }
443 }
444
445 foreach my $vol (sort keys %$local_volumes_errors) {
446 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
447 }
448 foreach my $err (@$other_errors) {
449 $self->log('warn', "$err");
450 }
451
452 if ($abort) {
453 die "can't migrate VM - check log\n";
454 }
455
456 # additional checks for local storage
457 foreach my $volid (keys %$local_volumes) {
458 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
459 my $scfg = PVE::Storage::storage_config($storecfg, $sid);
460
461 my $migratable = $scfg->{type} =~ /^(?:dir|zfspool|lvmthin|lvm)$/;
462
463 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
464 if !$migratable;
465
466 # image is a linked clone on local storage, se we can't migrate.
467 if (my $basename = (PVE::Storage::parse_volname($storecfg, $volid))[3]) {
468 die "can't migrate '$volid' as it's a clone of '$basename'";
469 }
470 }
471
472 if ($replication_jobcfg) {
473 if ($self->{running}) {
474
475 my $version = PVE::QemuServer::kvm_user_version();
476 if (!min_version($version, 4, 2)) {
477 die "can't live migrate VM with replicated volumes, pve-qemu to old (< 4.2)!\n"
478 }
479
480 my $live_replicatable_volumes = {};
481 PVE::QemuConfig->foreach_volume($conf, sub {
482 my ($ds, $drive) = @_;
483
484 my $volid = $drive->{file};
485 $live_replicatable_volumes->{$ds} = $volid
486 if defined($replicatable_volumes->{$volid});
487 });
488 foreach my $drive (keys %$live_replicatable_volumes) {
489 my $volid = $live_replicatable_volumes->{$drive};
490
491 my $bitmap = "repl_$drive";
492
493 # start tracking before replication to get full delta + a few duplicates
494 $self->log('info', "$drive: start tracking writes using block-dirty-bitmap '$bitmap'");
495 mon_cmd($vmid, 'block-dirty-bitmap-add', node => "drive-$drive", name => $bitmap);
496
497 # other info comes from target node in phase 2
498 $self->{target_drive}->{$drive}->{bitmap} = $bitmap;
499 }
500 }
501 $self->log('info', "replicating disk images");
502
503 my $start_time = time();
504 my $logfunc = sub { $self->log('info', shift) };
505 $self->{replicated_volumes} = PVE::Replication::run_replication(
506 'PVE::QemuConfig', $replication_jobcfg, $start_time, $start_time, $logfunc);
507 }
508
509 # sizes in config have to be accurate for remote node to correctly
510 # allocate disks, rescan to be sure
511 my $volid_hash = PVE::QemuServer::scan_volids($storecfg, $vmid);
512 PVE::QemuConfig->foreach_volume($conf, sub {
513 my ($key, $drive) = @_;
514 my ($updated, $old_size, $new_size) = PVE::QemuServer::Drive::update_disksize($drive, $volid_hash);
515 if (defined($updated)) {
516 $conf->{$key} = PVE::QemuServer::print_drive($updated);
517 $self->log('info', "size of disk '$updated->{file}' ($key) updated from $old_size to $new_size\n");
518 }
519 });
520
521 # we want to set the efidisk size in the config to the size of the
522 # real OVMF_VARS.fd image, else we can create a too big image, which does not work
523 if (defined($conf->{efidisk0})) {
524 PVE::QemuServer::update_efidisk_size($conf);
525 }
526
527 $self->log('info', "copying local disk images") if scalar(%$local_volumes);
528
529 foreach my $volid (keys %$local_volumes) {
530 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
531 my $targetsid = PVE::QemuServer::map_storage($self->{opts}->{storagemap}, $sid);
532 my $ref = $local_volumes->{$volid}->{ref};
533 if ($self->{running} && $ref eq 'config') {
534 push @{$self->{online_local_volumes}}, $volid;
535 } elsif ($ref eq 'generated') {
536 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n" if $self->{running};
537 # skip all generated volumes but queue them for deletion in phase3_cleanup
538 push @{$self->{volumes}}, $volid;
539 next;
540 } else {
541 next if $self->{replicated_volumes}->{$volid};
542 push @{$self->{volumes}}, $volid;
543 my $opts = $self->{opts};
544 my $insecure = $opts->{migration_type} eq 'insecure';
545 my $with_snapshots = $local_volumes->{$volid}->{snapshots};
546 # use 'migrate' limit for transfer to other node
547 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', [$targetsid, $sid], $opts->{bwlimit});
548 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
549 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
550
551 PVE::Storage::storage_migrate($storecfg, $volid, $self->{ssh_info}, $targetsid,
552 undef, undef, undef, $bwlimit, $insecure, $with_snapshots);
553 }
554 }
555 };
556 die "Failed to sync data - $@" if $@;
557 }
558
559 sub cleanup_remotedisks {
560 my ($self) = @_;
561
562 foreach my $target_drive (keys %{$self->{target_drive}}) {
563 my $drivestr = $self->{target_drive}->{$target_drive}->{drivestr};
564 next if !defined($drivestr);
565
566 my $drive = PVE::QemuServer::parse_drive($target_drive, $drivestr);
567
568 # don't clean up replicated disks!
569 next if defined($self->{replicated_volumes}->{$drive->{file}});
570
571 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
572
573 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
574
575 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
576 if (my $err = $@) {
577 $self->log('err', $err);
578 $self->{errors} = 1;
579 }
580 }
581 }
582
583 sub cleanup_bitmaps {
584 my ($self) = @_;
585 foreach my $drive (keys %{$self->{target_drive}}) {
586 my $bitmap = $self->{target_drive}->{$drive}->{bitmap};
587 next if !$bitmap;
588 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
589 mon_cmd($self->{vmid}, 'block-dirty-bitmap-remove', node => "drive-$drive", name => $bitmap);
590 }
591 }
592
593 sub phase1 {
594 my ($self, $vmid) = @_;
595
596 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
597
598 my $conf = $self->{vmconf};
599
600 # set migrate lock in config file
601 $conf->{lock} = 'migrate';
602 PVE::QemuConfig->write_config($vmid, $conf);
603
604 sync_disks($self, $vmid);
605
606 # sync_disks fixes disk sizes to match their actual size, write changes so
607 # target allocates correct volumes
608 PVE::QemuConfig->write_config($vmid, $conf);
609 };
610
611 sub phase1_cleanup {
612 my ($self, $vmid, $err) = @_;
613
614 $self->log('info', "aborting phase 1 - cleanup resources");
615
616 my $conf = $self->{vmconf};
617 delete $conf->{lock};
618 eval { PVE::QemuConfig->write_config($vmid, $conf) };
619 if (my $err = $@) {
620 $self->log('err', $err);
621 }
622
623 if ($self->{volumes}) {
624 foreach my $volid (@{$self->{volumes}}) {
625 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
626 # fixme: try to remove ?
627 }
628 }
629
630 eval { $self->cleanup_bitmaps() };
631 if (my $err =$@) {
632 $self->log('err', $err);
633 }
634
635 }
636
637 sub phase2 {
638 my ($self, $vmid) = @_;
639
640 my $conf = $self->{vmconf};
641
642 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
643
644 my $raddr;
645 my $rport;
646 my $ruri; # the whole migration dst. URI (protocol:address[:port])
647 my $nodename = PVE::INotify::nodename();
648
649 ## start on remote node
650 my $cmd = [@{$self->{rem_ssh}}];
651
652 my $spice_ticket;
653 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
654 my $res = mon_cmd($vmid, 'query-spice');
655 $spice_ticket = $res->{ticket};
656 }
657
658 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
659
660 my $migration_type = $self->{opts}->{migration_type};
661
662 push @$cmd, '--migration_type', $migration_type;
663
664 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
665 if $self->{opts}->{migration_network};
666
667 if ($migration_type eq 'insecure') {
668 push @$cmd, '--stateuri', 'tcp';
669 } else {
670 push @$cmd, '--stateuri', 'unix';
671 }
672
673 if ($self->{forcemachine}) {
674 push @$cmd, '--machine', $self->{forcemachine};
675 }
676
677 if ($self->{forcecpu}) {
678 push @$cmd, '--force-cpu', $self->{forcecpu};
679 }
680
681 if ($self->{online_local_volumes}) {
682 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
683 }
684
685 my $spice_port;
686 my $tunnel_addr = [];
687 my $sock_addr = [];
688 # version > 0 for unix socket support
689 my $nbd_protocol_version = 1;
690 # TODO change to 'spice_ticket: <ticket>\n' in 7.0
691 my $input = $spice_ticket ? "$spice_ticket\n" : "\n";
692 $input .= "nbd_protocol_version: $nbd_protocol_version\n";
693 foreach my $volid (keys %{$self->{replicated_volumes}}) {
694 $input .= "replicated_volume: $volid\n";
695 }
696
697 my $target_replicated_volumes = {};
698
699 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
700 # instead we pipe it through STDIN
701 my $exitcode = PVE::Tools::run_command($cmd, input => $input, outfunc => sub {
702 my $line = shift;
703
704 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
705 $raddr = $1;
706 $rport = int($2);
707 $ruri = "tcp:$raddr:$rport";
708 }
709 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
710 $raddr = $1;
711 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
712 $ruri = "unix:$raddr";
713 }
714 elsif ($line =~ m/^migration listens on port (\d+)$/) {
715 $raddr = "localhost";
716 $rport = int($1);
717 $ruri = "tcp:$raddr:$rport";
718 }
719 elsif ($line =~ m/^spice listens on port (\d+)$/) {
720 $spice_port = int($1);
721 }
722 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
723 my $drivestr = $4;
724 my $nbd_uri = "nbd:$1:$2:exportname=$3";
725 my $targetdrive = $3;
726 $targetdrive =~ s/drive-//g;
727
728 $self->{target_drive}->{$targetdrive}->{drivestr} = $drivestr;
729 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
730 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
731 my $drivestr = $4;
732 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
733 my $nbd_unix_addr = $1;
734 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
735 my $targetdrive = $3;
736 $targetdrive =~ s/drive-//g;
737
738 $self->{target_drive}->{$targetdrive}->{drivestr} = $drivestr;
739 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
740 push @$tunnel_addr, "$nbd_unix_addr:$nbd_unix_addr";
741 push @$sock_addr, $nbd_unix_addr;
742 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
743 my $drive = $1;
744 my $volid = $2;
745 $target_replicated_volumes->{$volid} = $drive;
746 } elsif ($line =~ m/^QEMU: (.*)$/) {
747 $self->log('info', "[$self->{node}] $1\n");
748 }
749 }, errfunc => sub {
750 my $line = shift;
751 $self->log('info', "[$self->{node}] $line");
752 }, noerr => 1);
753
754 die "remote command failed with exit code $exitcode\n" if $exitcode;
755
756 die "unable to detect remote migration address\n" if !$raddr;
757
758 if (scalar(keys %$target_replicated_volumes) != scalar(keys %{$self->{replicated_volumes}})) {
759 die "number of replicated disks on source and target node do not match - target node too old?\n"
760 }
761
762 $self->log('info', "start remote tunnel");
763
764 if ($migration_type eq 'secure') {
765
766 if ($ruri =~ /^unix:/) {
767 unlink $raddr;
768 push @$tunnel_addr, "$raddr:$raddr";
769 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
770 push @$sock_addr, $raddr;
771
772 my $unix_socket_try = 0; # wait for the socket to become ready
773 while ($unix_socket_try <= 100) {
774 $unix_socket_try++;
775 my $available = 0;
776 foreach my $sock (@$sock_addr) {
777 if (-S $sock) {
778 $available++;
779 }
780 }
781
782 if ($available == @$sock_addr) {
783 last;
784 }
785
786 usleep(50000);
787 }
788 if ($unix_socket_try > 100) {
789 $self->{errors} = 1;
790 $self->finish_tunnel($self->{tunnel});
791 die "Timeout, migration socket $ruri did not get ready";
792 }
793
794 } elsif ($ruri =~ /^tcp:/) {
795 my $tunnel_addr;
796 if ($raddr eq "localhost") {
797 # for backwards compatibility with older qemu-server versions
798 my $pfamily = PVE::Tools::get_host_address_family($nodename);
799 my $lport = PVE::Tools::next_migrate_port($pfamily);
800 $tunnel_addr = "$lport:localhost:$rport";
801 }
802
803 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
804
805 } else {
806 die "unsupported protocol in migration URI: $ruri\n";
807 }
808 } else {
809 #fork tunnel for insecure migration, to send faster commands like resume
810 $self->{tunnel} = $self->fork_tunnel();
811 }
812 $self->{tunnel}->{sock_addr} = $sock_addr if (@$sock_addr);
813
814 my $start = time();
815
816 my $opt_bwlimit = $self->{opts}->{bwlimit};
817
818 if (defined($self->{online_local_volumes})) {
819 $self->{storage_migration} = 1;
820 $self->{storage_migration_jobs} = {};
821 $self->log('info', "starting storage migration");
822
823 die "The number of local disks does not match between the source and the destination.\n"
824 if (scalar(keys %{$self->{target_drive}}) != scalar @{$self->{online_local_volumes}});
825 foreach my $drive (keys %{$self->{target_drive}}){
826 my $target = $self->{target_drive}->{$drive};
827 my $nbd_uri = $target->{nbd_uri};
828
829 my $source_drive = PVE::QemuServer::parse_drive($drive, $conf->{$drive});
830 my $target_drive = PVE::QemuServer::parse_drive($drive, $target->{drivestr});
831
832 my $source_sid = PVE::Storage::Plugin::parse_volume_id($source_drive->{file});
833 my $target_sid = PVE::Storage::Plugin::parse_volume_id($target_drive->{file});
834
835 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', [$source_sid, $target_sid], $opt_bwlimit);
836 my $bitmap = $target->{bitmap};
837
838 $self->log('info', "$drive: start migration to $nbd_uri");
839 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 'skip', undef, $bwlimit, $bitmap);
840 }
841 }
842
843 $self->log('info', "starting online/live migration on $ruri");
844 $self->{livemigration} = 1;
845
846 # load_defaults
847 my $defaults = PVE::QemuServer::load_defaults();
848
849 $self->log('info', "set migration_caps");
850 eval {
851 PVE::QemuServer::set_migration_caps($vmid);
852 };
853 warn $@ if $@;
854
855 my $qemu_migrate_params = {};
856
857 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
858 # migrate_speed parameter in qm.conf - take the lower of the two.
859 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', undef, $opt_bwlimit) // 0;
860 my $migrate_speed = $conf->{migrate_speed} // $bwlimit;
861 # migrate_speed is in MB/s, bwlimit in KB/s
862 $migrate_speed *= 1024;
863
864 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
865
866 # always set migrate speed (overwrite kvm default of 32m) we set a very high
867 # default of 8192m which is basically unlimited
868 $migrate_speed ||= ($defaults->{migrate_speed} || 8192) * 1024;
869
870 # qmp takes migrate_speed in B/s.
871 $migrate_speed *= 1024;
872 $self->log('info', "migration speed limit: $migrate_speed B/s");
873 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
874
875 my $migrate_downtime = $defaults->{migrate_downtime};
876 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
877 # migrate-set-parameters expects limit in ms
878 $migrate_downtime *= 1000;
879 $self->log('info', "migration downtime limit: $migrate_downtime ms");
880 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
881
882 # set cachesize to 10% of the total memory
883 my $memory = $conf->{memory} || $defaults->{memory};
884 my $cachesize = int($memory * 1048576 / 10);
885 $cachesize = round_powerof2($cachesize);
886
887 $self->log('info', "migration cachesize: $cachesize B");
888 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
889
890 $self->log('info', "set migration parameters");
891 eval {
892 mon_cmd($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
893 };
894 $self->log('info', "migrate-set-parameters error: $@") if $@;
895
896 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
897 my $rpcenv = PVE::RPCEnvironment::get();
898 my $authuser = $rpcenv->get_user();
899
900 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
901
902 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
903 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
904
905 $self->log('info', "spice client_migrate_info");
906
907 eval {
908 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
909 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
910 'cert-subject' => $subject);
911 };
912 $self->log('info', "client_migrate_info error: $@") if $@;
913
914 }
915
916 $self->log('info', "start migrate command to $ruri");
917 eval {
918 mon_cmd($vmid, "migrate", uri => $ruri);
919 };
920 my $merr = $@;
921 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
922
923 my $lstat = 0;
924 my $usleep = 1000000;
925 my $i = 0;
926 my $err_count = 0;
927 my $lastrem = undef;
928 my $downtimecounter = 0;
929 while (1) {
930 $i++;
931 my $avglstat = $lstat/$i if $lstat;
932
933 usleep($usleep);
934 my $stat;
935 eval {
936 $stat = mon_cmd($vmid, "query-migrate");
937 };
938 if (my $err = $@) {
939 $err_count++;
940 warn "query migrate failed: $err\n";
941 $self->log('info', "query migrate failed: $err");
942 if ($err_count <= 5) {
943 usleep(1000000);
944 next;
945 }
946 die "too many query migrate failures - aborting\n";
947 }
948
949 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
950 sleep(1);
951 next;
952 }
953
954 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
955 $merr = undef;
956 $err_count = 0;
957 if ($stat->{status} eq 'completed') {
958 my $delay = time() - $start;
959 if ($delay > 0) {
960 my $mbps = sprintf "%.2f", $memory / $delay;
961 my $downtime = $stat->{downtime} || 0;
962 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
963 }
964 }
965
966 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
967 $self->log('info', "migration status error: $stat->{status}");
968 die "aborting\n"
969 }
970
971 if ($stat->{status} ne 'active') {
972 $self->log('info', "migration status: $stat->{status}");
973 last;
974 }
975
976 if ($stat->{ram}->{transferred} ne $lstat) {
977 my $trans = $stat->{ram}->{transferred} || 0;
978 my $rem = $stat->{ram}->{remaining} || 0;
979 my $total = $stat->{ram}->{total} || 0;
980 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
981 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
982 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
983 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
984 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
985 # reduce sleep if remainig memory is lower than the average transfer speed
986 $usleep = 100000 if $avglstat && $rem < $avglstat;
987
988 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
989 "remaining ${rem}), total ${total})");
990
991 if (${xbzrlecachesize}) {
992 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
993 }
994
995 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
996 $downtimecounter++;
997 }
998 $lastrem = $rem;
999
1000 if ($downtimecounter > 5) {
1001 $downtimecounter = 0;
1002 $migrate_downtime *= 2;
1003 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1004 eval {
1005 # migrate-set-parameters does not touch values not
1006 # specified, so this only changes downtime-limit
1007 mon_cmd($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1008 };
1009 $self->log('info', "migrate-set-parameters error: $@") if $@;
1010 }
1011
1012 }
1013
1014
1015 $lstat = $stat->{ram}->{transferred};
1016
1017 } else {
1018 die $merr if $merr;
1019 die "unable to parse migration status '$stat->{status}' - aborting\n";
1020 }
1021 }
1022 }
1023
1024 sub phase2_cleanup {
1025 my ($self, $vmid, $err) = @_;
1026
1027 return if !$self->{errors};
1028 $self->{phase2errors} = 1;
1029
1030 $self->log('info', "aborting phase 2 - cleanup resources");
1031
1032 $self->log('info', "migrate_cancel");
1033 eval {
1034 mon_cmd($vmid, "migrate_cancel");
1035 };
1036 $self->log('info', "migrate_cancel error: $@") if $@;
1037
1038 my $conf = $self->{vmconf};
1039 delete $conf->{lock};
1040 eval { PVE::QemuConfig->write_config($vmid, $conf) };
1041 if (my $err = $@) {
1042 $self->log('err', $err);
1043 }
1044
1045 # cleanup ressources on target host
1046 if ($self->{storage_migration}) {
1047 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1048 if (my $err = $@) {
1049 $self->log('err', $err);
1050 }
1051 }
1052
1053 eval { $self->cleanup_bitmaps() };
1054 if (my $err =$@) {
1055 $self->log('err', $err);
1056 }
1057
1058 my $nodename = PVE::INotify::nodename();
1059
1060 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1061 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1062 if (my $err = $@) {
1063 $self->log('err', $err);
1064 $self->{errors} = 1;
1065 }
1066
1067 # cleanup after stopping, otherwise disks might be in-use by target VM!
1068 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1069 if (my $err = $@) {
1070 $self->log('err', $err);
1071 }
1072
1073
1074 if ($self->{tunnel}) {
1075 eval { finish_tunnel($self, $self->{tunnel}); };
1076 if (my $err = $@) {
1077 $self->log('err', $err);
1078 $self->{errors} = 1;
1079 }
1080 }
1081 }
1082
1083 sub phase3 {
1084 my ($self, $vmid) = @_;
1085
1086 my $volids = $self->{volumes};
1087 return if $self->{phase2errors};
1088
1089 # destroy local copies
1090 foreach my $volid (@$volids) {
1091 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1092 if (my $err = $@) {
1093 $self->log('err', "removing local copy of '$volid' failed - $err");
1094 $self->{errors} = 1;
1095 last if $err =~ /^interrupted by signal$/;
1096 }
1097 }
1098 }
1099
1100 sub phase3_cleanup {
1101 my ($self, $vmid, $err) = @_;
1102
1103 my $conf = $self->{vmconf};
1104 return if $self->{phase2errors};
1105
1106 my $tunnel = $self->{tunnel};
1107
1108 if ($self->{storage_migration}) {
1109 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1110 # to avoid it trying to re-establish it. We are in blockjob ready state,
1111 # thus, this command changes to it to blockjob complete (see qapi docs)
1112 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}, 'cancel'); };
1113
1114 if (my $err = $@) {
1115 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1116 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1117 die "Failed to complete storage migration: $err\n";
1118 } else {
1119 foreach my $target_drive (keys %{$self->{target_drive}}) {
1120 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{drivestr});
1121 $conf->{$target_drive} = PVE::QemuServer::print_drive($drive);
1122 PVE::QemuConfig->write_config($vmid, $conf);
1123 }
1124 }
1125 }
1126
1127 # transfer replication state before move config
1128 $self->transfer_replication_state() if $self->{replicated_volumes};
1129
1130 # move config to remote node
1131 my $conffile = PVE::QemuConfig->config_file($vmid);
1132 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
1133
1134 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
1135 if !rename($conffile, $newconffile);
1136
1137 $self->switch_replication_job_target() if $self->{replicated_volumes};
1138
1139 if ($self->{livemigration}) {
1140 if ($self->{storage_migration}) {
1141 # stop nbd server on remote vm - requirement for resume since 2.9
1142 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
1143
1144 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1145 if (my $err = $@) {
1146 $self->log('err', $err);
1147 $self->{errors} = 1;
1148 }
1149 }
1150
1151 # config moved and nbd server stopped - now we can resume vm on target
1152 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
1153 eval {
1154 $self->write_tunnel($tunnel, 30, "resume $vmid");
1155 };
1156 if (my $err = $@) {
1157 $self->log('err', $err);
1158 $self->{errors} = 1;
1159 }
1160 } else {
1161 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1162 my $logf = sub {
1163 my $line = shift;
1164 $self->log('err', $line);
1165 };
1166 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
1167 if (my $err = $@) {
1168 $self->log('err', $err);
1169 $self->{errors} = 1;
1170 }
1171 }
1172
1173 if ($self->{storage_migration} && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks} && $self->{running}) {
1174 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1175 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1176 }
1177 }
1178
1179 # close tunnel on successful migration, on error phase2_cleanup closed it
1180 if ($tunnel) {
1181 eval { finish_tunnel($self, $tunnel); };
1182 if (my $err = $@) {
1183 $self->log('err', $err);
1184 $self->{errors} = 1;
1185 }
1186 }
1187
1188 eval {
1189 my $timer = 0;
1190 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1191 $self->log('info', "Waiting for spice server migration");
1192 while (1) {
1193 my $res = mon_cmd($vmid, 'query-spice');
1194 last if int($res->{'migrated'}) == 1;
1195 last if $timer > 50;
1196 $timer ++;
1197 usleep(200000);
1198 }
1199 }
1200 };
1201
1202 # always stop local VM
1203 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1204 if (my $err = $@) {
1205 $self->log('err', "stopping vm failed - $err");
1206 $self->{errors} = 1;
1207 }
1208
1209 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1210 eval {
1211 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
1212 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
1213 };
1214 if (my $err = $@) {
1215 $self->log('err', $err);
1216 $self->{errors} = 1;
1217 }
1218
1219 if($self->{storage_migration}) {
1220 # destroy local copies
1221 my $volids = $self->{online_local_volumes};
1222
1223 foreach my $volid (@$volids) {
1224 # keep replicated volumes!
1225 next if $self->{replicated_volumes}->{$volid};
1226
1227 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1228 if (my $err = $@) {
1229 $self->log('err', "removing local copy of '$volid' failed - $err");
1230 $self->{errors} = 1;
1231 last if $err =~ /^interrupted by signal$/;
1232 }
1233 }
1234
1235 }
1236
1237 # clear migrate lock
1238 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1239 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1240 }
1241
1242 sub final_cleanup {
1243 my ($self, $vmid) = @_;
1244
1245 # nothing to do
1246 }
1247
1248 sub round_powerof2 {
1249 return 1 if $_[0] < 2;
1250 return 2 << int(log($_[0]-1)/log(2));
1251 }
1252
1253 1;