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