]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
Use new storage_migrate interface
[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 # use 'migrate' limit for transfer to other node
545 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', [$targetsid, $sid], $opts->{bwlimit});
546 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
547 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
548
549 my $storage_migrate_opts = {
550 'bwlimit' => $bwlimit,
551 'insecure' => $opts->{migration_type} eq 'insecure',
552 'with_snapshots' => $local_volumes->{$volid}->{snapshots},
553 };
554
555 PVE::Storage::storage_migrate($storecfg, $volid, $self->{ssh_info},
556 $targetsid, $storage_migrate_opts);
557 }
558 }
559 };
560 die "Failed to sync data - $@" if $@;
561 }
562
563 sub cleanup_remotedisks {
564 my ($self) = @_;
565
566 foreach my $target_drive (keys %{$self->{target_drive}}) {
567 my $drivestr = $self->{target_drive}->{$target_drive}->{drivestr};
568 next if !defined($drivestr);
569
570 my $drive = PVE::QemuServer::parse_drive($target_drive, $drivestr);
571
572 # don't clean up replicated disks!
573 next if defined($self->{replicated_volumes}->{$drive->{file}});
574
575 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
576
577 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
578
579 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
580 if (my $err = $@) {
581 $self->log('err', $err);
582 $self->{errors} = 1;
583 }
584 }
585 }
586
587 sub cleanup_bitmaps {
588 my ($self) = @_;
589 foreach my $drive (keys %{$self->{target_drive}}) {
590 my $bitmap = $self->{target_drive}->{$drive}->{bitmap};
591 next if !$bitmap;
592 $self->log('info', "$drive: removing block-dirty-bitmap '$bitmap'");
593 mon_cmd($self->{vmid}, 'block-dirty-bitmap-remove', node => "drive-$drive", name => $bitmap);
594 }
595 }
596
597 sub phase1 {
598 my ($self, $vmid) = @_;
599
600 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
601
602 my $conf = $self->{vmconf};
603
604 # set migrate lock in config file
605 $conf->{lock} = 'migrate';
606 PVE::QemuConfig->write_config($vmid, $conf);
607
608 sync_disks($self, $vmid);
609
610 # sync_disks fixes disk sizes to match their actual size, write changes so
611 # target allocates correct volumes
612 PVE::QemuConfig->write_config($vmid, $conf);
613 };
614
615 sub phase1_cleanup {
616 my ($self, $vmid, $err) = @_;
617
618 $self->log('info', "aborting phase 1 - cleanup resources");
619
620 my $conf = $self->{vmconf};
621 delete $conf->{lock};
622 eval { PVE::QemuConfig->write_config($vmid, $conf) };
623 if (my $err = $@) {
624 $self->log('err', $err);
625 }
626
627 if ($self->{volumes}) {
628 foreach my $volid (@{$self->{volumes}}) {
629 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
630 # fixme: try to remove ?
631 }
632 }
633
634 eval { $self->cleanup_bitmaps() };
635 if (my $err =$@) {
636 $self->log('err', $err);
637 }
638
639 }
640
641 sub phase2 {
642 my ($self, $vmid) = @_;
643
644 my $conf = $self->{vmconf};
645
646 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
647
648 my $raddr;
649 my $rport;
650 my $ruri; # the whole migration dst. URI (protocol:address[:port])
651 my $nodename = PVE::INotify::nodename();
652
653 ## start on remote node
654 my $cmd = [@{$self->{rem_ssh}}];
655
656 my $spice_ticket;
657 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
658 my $res = mon_cmd($vmid, 'query-spice');
659 $spice_ticket = $res->{ticket};
660 }
661
662 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
663
664 my $migration_type = $self->{opts}->{migration_type};
665
666 push @$cmd, '--migration_type', $migration_type;
667
668 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
669 if $self->{opts}->{migration_network};
670
671 if ($migration_type eq 'insecure') {
672 push @$cmd, '--stateuri', 'tcp';
673 } else {
674 push @$cmd, '--stateuri', 'unix';
675 }
676
677 if ($self->{forcemachine}) {
678 push @$cmd, '--machine', $self->{forcemachine};
679 }
680
681 if ($self->{forcecpu}) {
682 push @$cmd, '--force-cpu', $self->{forcecpu};
683 }
684
685 if ($self->{online_local_volumes}) {
686 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
687 }
688
689 my $spice_port;
690 my $tunnel_addr = [];
691 my $sock_addr = [];
692 # version > 0 for unix socket support
693 my $nbd_protocol_version = 1;
694 # TODO change to 'spice_ticket: <ticket>\n' in 7.0
695 my $input = $spice_ticket ? "$spice_ticket\n" : "\n";
696 $input .= "nbd_protocol_version: $nbd_protocol_version\n";
697 foreach my $volid (keys %{$self->{replicated_volumes}}) {
698 $input .= "replicated_volume: $volid\n";
699 }
700
701 my $target_replicated_volumes = {};
702
703 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
704 # instead we pipe it through STDIN
705 my $exitcode = PVE::Tools::run_command($cmd, input => $input, outfunc => sub {
706 my $line = shift;
707
708 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
709 $raddr = $1;
710 $rport = int($2);
711 $ruri = "tcp:$raddr:$rport";
712 }
713 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
714 $raddr = $1;
715 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
716 $ruri = "unix:$raddr";
717 }
718 elsif ($line =~ m/^migration listens on port (\d+)$/) {
719 $raddr = "localhost";
720 $rport = int($1);
721 $ruri = "tcp:$raddr:$rport";
722 }
723 elsif ($line =~ m/^spice listens on port (\d+)$/) {
724 $spice_port = int($1);
725 }
726 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
727 my $drivestr = $4;
728 my $nbd_uri = "nbd:$1:$2:exportname=$3";
729 my $targetdrive = $3;
730 $targetdrive =~ s/drive-//g;
731
732 $self->{target_drive}->{$targetdrive}->{drivestr} = $drivestr;
733 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
734 } elsif ($line =~ m!^storage migration listens on nbd:unix:(/run/qemu-server/(\d+)_nbd\.migrate):exportname=(\S+) volume:(\S+)$!) {
735 my $drivestr = $4;
736 die "Destination UNIX socket's VMID does not match source VMID" if $vmid ne $2;
737 my $nbd_unix_addr = $1;
738 my $nbd_uri = "nbd:unix:$nbd_unix_addr:exportname=$3";
739 my $targetdrive = $3;
740 $targetdrive =~ s/drive-//g;
741
742 $self->{target_drive}->{$targetdrive}->{drivestr} = $drivestr;
743 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
744 push @$tunnel_addr, "$nbd_unix_addr:$nbd_unix_addr";
745 push @$sock_addr, $nbd_unix_addr;
746 } elsif ($line =~ m/^re-using replicated volume: (\S+) - (.*)$/) {
747 my $drive = $1;
748 my $volid = $2;
749 $target_replicated_volumes->{$volid} = $drive;
750 } elsif ($line =~ m/^QEMU: (.*)$/) {
751 $self->log('info', "[$self->{node}] $1\n");
752 }
753 }, errfunc => sub {
754 my $line = shift;
755 $self->log('info', "[$self->{node}] $line");
756 }, noerr => 1);
757
758 die "remote command failed with exit code $exitcode\n" if $exitcode;
759
760 die "unable to detect remote migration address\n" if !$raddr;
761
762 if (scalar(keys %$target_replicated_volumes) != scalar(keys %{$self->{replicated_volumes}})) {
763 die "number of replicated disks on source and target node do not match - target node too old?\n"
764 }
765
766 $self->log('info', "start remote tunnel");
767
768 if ($migration_type eq 'secure') {
769
770 if ($ruri =~ /^unix:/) {
771 unlink $raddr;
772 push @$tunnel_addr, "$raddr:$raddr";
773 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
774 push @$sock_addr, $raddr;
775
776 my $unix_socket_try = 0; # wait for the socket to become ready
777 while ($unix_socket_try <= 100) {
778 $unix_socket_try++;
779 my $available = 0;
780 foreach my $sock (@$sock_addr) {
781 if (-S $sock) {
782 $available++;
783 }
784 }
785
786 if ($available == @$sock_addr) {
787 last;
788 }
789
790 usleep(50000);
791 }
792 if ($unix_socket_try > 100) {
793 $self->{errors} = 1;
794 $self->finish_tunnel($self->{tunnel});
795 die "Timeout, migration socket $ruri did not get ready";
796 }
797
798 } elsif ($ruri =~ /^tcp:/) {
799 my $tunnel_addr;
800 if ($raddr eq "localhost") {
801 # for backwards compatibility with older qemu-server versions
802 my $pfamily = PVE::Tools::get_host_address_family($nodename);
803 my $lport = PVE::Tools::next_migrate_port($pfamily);
804 $tunnel_addr = "$lport:localhost:$rport";
805 }
806
807 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
808
809 } else {
810 die "unsupported protocol in migration URI: $ruri\n";
811 }
812 } else {
813 #fork tunnel for insecure migration, to send faster commands like resume
814 $self->{tunnel} = $self->fork_tunnel();
815 }
816 $self->{tunnel}->{sock_addr} = $sock_addr if (@$sock_addr);
817
818 my $start = time();
819
820 my $opt_bwlimit = $self->{opts}->{bwlimit};
821
822 if (defined($self->{online_local_volumes})) {
823 $self->{storage_migration} = 1;
824 $self->{storage_migration_jobs} = {};
825 $self->log('info', "starting storage migration");
826
827 die "The number of local disks does not match between the source and the destination.\n"
828 if (scalar(keys %{$self->{target_drive}}) != scalar @{$self->{online_local_volumes}});
829 foreach my $drive (keys %{$self->{target_drive}}){
830 my $target = $self->{target_drive}->{$drive};
831 my $nbd_uri = $target->{nbd_uri};
832
833 my $source_drive = PVE::QemuServer::parse_drive($drive, $conf->{$drive});
834 my $target_drive = PVE::QemuServer::parse_drive($drive, $target->{drivestr});
835
836 my $source_sid = PVE::Storage::Plugin::parse_volume_id($source_drive->{file});
837 my $target_sid = PVE::Storage::Plugin::parse_volume_id($target_drive->{file});
838
839 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', [$source_sid, $target_sid], $opt_bwlimit);
840 my $bitmap = $target->{bitmap};
841
842 $self->log('info', "$drive: start migration to $nbd_uri");
843 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 'skip', undef, $bwlimit, $bitmap);
844 }
845 }
846
847 $self->log('info', "starting online/live migration on $ruri");
848 $self->{livemigration} = 1;
849
850 # load_defaults
851 my $defaults = PVE::QemuServer::load_defaults();
852
853 $self->log('info', "set migration_caps");
854 eval {
855 PVE::QemuServer::set_migration_caps($vmid);
856 };
857 warn $@ if $@;
858
859 my $qemu_migrate_params = {};
860
861 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
862 # migrate_speed parameter in qm.conf - take the lower of the two.
863 my $bwlimit = PVE::Storage::get_bandwidth_limit('migration', undef, $opt_bwlimit) // 0;
864 my $migrate_speed = $conf->{migrate_speed} // $bwlimit;
865 # migrate_speed is in MB/s, bwlimit in KB/s
866 $migrate_speed *= 1024;
867
868 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
869
870 # always set migrate speed (overwrite kvm default of 32m) we set a very high
871 # default of 8192m which is basically unlimited
872 $migrate_speed ||= ($defaults->{migrate_speed} || 8192) * 1024;
873
874 # qmp takes migrate_speed in B/s.
875 $migrate_speed *= 1024;
876 $self->log('info', "migration speed limit: $migrate_speed B/s");
877 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
878
879 my $migrate_downtime = $defaults->{migrate_downtime};
880 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
881 # migrate-set-parameters expects limit in ms
882 $migrate_downtime *= 1000;
883 $self->log('info', "migration downtime limit: $migrate_downtime ms");
884 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
885
886 # set cachesize to 10% of the total memory
887 my $memory = $conf->{memory} || $defaults->{memory};
888 my $cachesize = int($memory * 1048576 / 10);
889 $cachesize = round_powerof2($cachesize);
890
891 $self->log('info', "migration cachesize: $cachesize B");
892 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
893
894 $self->log('info', "set migration parameters");
895 eval {
896 mon_cmd($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
897 };
898 $self->log('info', "migrate-set-parameters error: $@") if $@;
899
900 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
901 my $rpcenv = PVE::RPCEnvironment::get();
902 my $authuser = $rpcenv->get_user();
903
904 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
905
906 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
907 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
908
909 $self->log('info', "spice client_migrate_info");
910
911 eval {
912 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
913 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
914 'cert-subject' => $subject);
915 };
916 $self->log('info', "client_migrate_info error: $@") if $@;
917
918 }
919
920 $self->log('info', "start migrate command to $ruri");
921 eval {
922 mon_cmd($vmid, "migrate", uri => $ruri);
923 };
924 my $merr = $@;
925 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
926
927 my $lstat = 0;
928 my $usleep = 1000000;
929 my $i = 0;
930 my $err_count = 0;
931 my $lastrem = undef;
932 my $downtimecounter = 0;
933 while (1) {
934 $i++;
935 my $avglstat = $lstat/$i if $lstat;
936
937 usleep($usleep);
938 my $stat;
939 eval {
940 $stat = mon_cmd($vmid, "query-migrate");
941 };
942 if (my $err = $@) {
943 $err_count++;
944 warn "query migrate failed: $err\n";
945 $self->log('info', "query migrate failed: $err");
946 if ($err_count <= 5) {
947 usleep(1000000);
948 next;
949 }
950 die "too many query migrate failures - aborting\n";
951 }
952
953 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
954 sleep(1);
955 next;
956 }
957
958 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
959 $merr = undef;
960 $err_count = 0;
961 if ($stat->{status} eq 'completed') {
962 my $delay = time() - $start;
963 if ($delay > 0) {
964 my $mbps = sprintf "%.2f", $memory / $delay;
965 my $downtime = $stat->{downtime} || 0;
966 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
967 }
968 }
969
970 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
971 $self->log('info', "migration status error: $stat->{status}");
972 die "aborting\n"
973 }
974
975 if ($stat->{status} ne 'active') {
976 $self->log('info', "migration status: $stat->{status}");
977 last;
978 }
979
980 if ($stat->{ram}->{transferred} ne $lstat) {
981 my $trans = $stat->{ram}->{transferred} || 0;
982 my $rem = $stat->{ram}->{remaining} || 0;
983 my $total = $stat->{ram}->{total} || 0;
984 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
985 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
986 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
987 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
988 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
989 # reduce sleep if remainig memory is lower than the average transfer speed
990 $usleep = 100000 if $avglstat && $rem < $avglstat;
991
992 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
993 "remaining ${rem}), total ${total})");
994
995 if (${xbzrlecachesize}) {
996 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
997 }
998
999 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
1000 $downtimecounter++;
1001 }
1002 $lastrem = $rem;
1003
1004 if ($downtimecounter > 5) {
1005 $downtimecounter = 0;
1006 $migrate_downtime *= 2;
1007 $self->log('info', "auto-increased downtime to continue migration: $migrate_downtime ms");
1008 eval {
1009 # migrate-set-parameters does not touch values not
1010 # specified, so this only changes downtime-limit
1011 mon_cmd($vmid, "migrate-set-parameters", 'downtime-limit' => int($migrate_downtime));
1012 };
1013 $self->log('info', "migrate-set-parameters error: $@") if $@;
1014 }
1015
1016 }
1017
1018
1019 $lstat = $stat->{ram}->{transferred};
1020
1021 } else {
1022 die $merr if $merr;
1023 die "unable to parse migration status '$stat->{status}' - aborting\n";
1024 }
1025 }
1026 }
1027
1028 sub phase2_cleanup {
1029 my ($self, $vmid, $err) = @_;
1030
1031 return if !$self->{errors};
1032 $self->{phase2errors} = 1;
1033
1034 $self->log('info', "aborting phase 2 - cleanup resources");
1035
1036 $self->log('info', "migrate_cancel");
1037 eval {
1038 mon_cmd($vmid, "migrate_cancel");
1039 };
1040 $self->log('info', "migrate_cancel error: $@") if $@;
1041
1042 my $conf = $self->{vmconf};
1043 delete $conf->{lock};
1044 eval { PVE::QemuConfig->write_config($vmid, $conf) };
1045 if (my $err = $@) {
1046 $self->log('err', $err);
1047 }
1048
1049 # cleanup ressources on target host
1050 if ($self->{storage_migration}) {
1051 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1052 if (my $err = $@) {
1053 $self->log('err', $err);
1054 }
1055 }
1056
1057 eval { $self->cleanup_bitmaps() };
1058 if (my $err =$@) {
1059 $self->log('err', $err);
1060 }
1061
1062 my $nodename = PVE::INotify::nodename();
1063
1064 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
1065 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1066 if (my $err = $@) {
1067 $self->log('err', $err);
1068 $self->{errors} = 1;
1069 }
1070
1071 # cleanup after stopping, otherwise disks might be in-use by target VM!
1072 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1073 if (my $err = $@) {
1074 $self->log('err', $err);
1075 }
1076
1077
1078 if ($self->{tunnel}) {
1079 eval { finish_tunnel($self, $self->{tunnel}); };
1080 if (my $err = $@) {
1081 $self->log('err', $err);
1082 $self->{errors} = 1;
1083 }
1084 }
1085 }
1086
1087 sub phase3 {
1088 my ($self, $vmid) = @_;
1089
1090 my $volids = $self->{volumes};
1091 return if $self->{phase2errors};
1092
1093 # destroy local copies
1094 foreach my $volid (@$volids) {
1095 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1096 if (my $err = $@) {
1097 $self->log('err', "removing local copy of '$volid' failed - $err");
1098 $self->{errors} = 1;
1099 last if $err =~ /^interrupted by signal$/;
1100 }
1101 }
1102 }
1103
1104 sub phase3_cleanup {
1105 my ($self, $vmid, $err) = @_;
1106
1107 my $conf = $self->{vmconf};
1108 return if $self->{phase2errors};
1109
1110 my $tunnel = $self->{tunnel};
1111
1112 if ($self->{storage_migration}) {
1113 # finish block-job with block-job-cancel, to disconnect source VM from NBD
1114 # to avoid it trying to re-establish it. We are in blockjob ready state,
1115 # thus, this command changes to it to blockjob complete (see qapi docs)
1116 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}, 'cancel'); };
1117
1118 if (my $err = $@) {
1119 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
1120 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
1121 die "Failed to complete storage migration: $err\n";
1122 } else {
1123 foreach my $target_drive (keys %{$self->{target_drive}}) {
1124 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{drivestr});
1125 $conf->{$target_drive} = PVE::QemuServer::print_drive($drive);
1126 PVE::QemuConfig->write_config($vmid, $conf);
1127 }
1128 }
1129 }
1130
1131 # transfer replication state before move config
1132 $self->transfer_replication_state() if $self->{replicated_volumes};
1133
1134 # move config to remote node
1135 my $conffile = PVE::QemuConfig->config_file($vmid);
1136 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
1137
1138 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
1139 if !rename($conffile, $newconffile);
1140
1141 $self->switch_replication_job_target() if $self->{replicated_volumes};
1142
1143 if ($self->{livemigration}) {
1144 if ($self->{storage_migration}) {
1145 # stop nbd server on remote vm - requirement for resume since 2.9
1146 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
1147
1148 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1149 if (my $err = $@) {
1150 $self->log('err', $err);
1151 $self->{errors} = 1;
1152 }
1153 }
1154
1155 # config moved and nbd server stopped - now we can resume vm on target
1156 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
1157 eval {
1158 $self->write_tunnel($tunnel, 30, "resume $vmid");
1159 };
1160 if (my $err = $@) {
1161 $self->log('err', $err);
1162 $self->{errors} = 1;
1163 }
1164 } else {
1165 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1166 my $logf = sub {
1167 my $line = shift;
1168 $self->log('err', $line);
1169 };
1170 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
1171 if (my $err = $@) {
1172 $self->log('err', $err);
1173 $self->{errors} = 1;
1174 }
1175 }
1176
1177 if ($self->{storage_migration} && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks} && $self->{running}) {
1178 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1179 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1180 }
1181 }
1182
1183 # close tunnel on successful migration, on error phase2_cleanup closed it
1184 if ($tunnel) {
1185 eval { finish_tunnel($self, $tunnel); };
1186 if (my $err = $@) {
1187 $self->log('err', $err);
1188 $self->{errors} = 1;
1189 }
1190 }
1191
1192 eval {
1193 my $timer = 0;
1194 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1195 $self->log('info', "Waiting for spice server migration");
1196 while (1) {
1197 my $res = mon_cmd($vmid, 'query-spice');
1198 last if int($res->{'migrated'}) == 1;
1199 last if $timer > 50;
1200 $timer ++;
1201 usleep(200000);
1202 }
1203 }
1204 };
1205
1206 # always stop local VM
1207 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1208 if (my $err = $@) {
1209 $self->log('err', "stopping vm failed - $err");
1210 $self->{errors} = 1;
1211 }
1212
1213 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1214 eval {
1215 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
1216 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
1217 };
1218 if (my $err = $@) {
1219 $self->log('err', $err);
1220 $self->{errors} = 1;
1221 }
1222
1223 if($self->{storage_migration}) {
1224 # destroy local copies
1225 my $volids = $self->{online_local_volumes};
1226
1227 foreach my $volid (@$volids) {
1228 # keep replicated volumes!
1229 next if $self->{replicated_volumes}->{$volid};
1230
1231 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1232 if (my $err = $@) {
1233 $self->log('err', "removing local copy of '$volid' failed - $err");
1234 $self->{errors} = 1;
1235 last if $err =~ /^interrupted by signal$/;
1236 }
1237 }
1238
1239 }
1240
1241 # clear migrate lock
1242 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1243 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1244 }
1245
1246 sub final_cleanup {
1247 my ($self, $vmid) = @_;
1248
1249 # nothing to do
1250 }
1251
1252 sub round_powerof2 {
1253 return 1 if $_[0] < 2;
1254 return 2 << int(log($_[0]-1)/log(2));
1255 }
1256
1257 1;