1 package PVE
::QemuMigrate
;
5 use PVE
::AbstractMigrate
;
8 use POSIX
qw( WNOHANG );
14 use PVE
::QemuServer
::Drive
;
15 use PVE
::QemuServer
::Machine
;
16 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
17 use Time
::HiRes
qw( usleep );
18 use PVE
::RPCEnvironment
;
19 use PVE
::ReplicationConfig
;
20 use PVE
::ReplicationState
;
23 use base
qw(PVE::AbstractMigrate);
25 sub fork_command_pipe
{
26 my ($self, $cmd) = @_;
28 my $reader = IO
::File-
>new();
29 my $writer = IO
::File-
>new();
35 eval { $cpid = open2
($reader, $writer, @$cmd); };
40 if ($orig_pid != $$) {
41 $self->log('err', "can't fork command pipe\n");
48 return { writer
=> $writer, reader
=> $reader, pid
=> $cpid };
51 sub finish_command_pipe
{
52 my ($self, $cmdpipe, $timeout) = @_;
54 my $cpid = $cmdpipe->{pid
};
55 return if !defined($cpid);
57 my $writer = $cmdpipe->{writer
};
58 my $reader = $cmdpipe->{reader
};
63 my $collect_child_process = sub {
64 my $res = waitpid($cpid, WNOHANG
);
65 if (defined($res) && ($res == $cpid)) {
66 delete $cmdpipe->{cpid
};
74 for (my $i = 0; $i < $timeout; $i++) {
75 return if &$collect_child_process();
80 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
84 for (my $i = 0; $i < 10; $i++) {
85 return if &$collect_child_process();
89 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
93 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
94 if !&$collect_child_process();
98 my ($self, $tunnel, $timeout) = @_;
100 $timeout = 60 if !defined($timeout);
102 my $reader = $tunnel->{reader
};
106 PVE
::Tools
::run_with_timeout
($timeout, sub { $output = <$reader>; });
108 die "reading from tunnel failed: $@\n" if $@;
116 my ($self, $tunnel, $timeout, $command) = @_;
118 $timeout = 60 if !defined($timeout);
120 my $writer = $tunnel->{writer
};
123 PVE
::Tools
::run_with_timeout
($timeout, sub {
124 print $writer "$command\n";
128 die "writing to tunnel failed: $@\n" if $@;
130 if ($tunnel->{version
} && $tunnel->{version
} >= 1) {
131 my $res = eval { $self->read_tunnel($tunnel, 10); };
132 die "no reply to command '$command': $@\n" if $@;
137 die "tunnel replied '$res' to command '$command'\n";
143 my ($self, $tunnel_addr) = @_;
145 my @localtunnelinfo = defined($tunnel_addr) ?
('-L' , $tunnel_addr ) : ();
147 my $cmd = [@{$self->{rem_ssh
}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, '/usr/sbin/qm', 'mtunnel' ];
149 my $tunnel = $self->fork_command_pipe($cmd);
152 my $helo = $self->read_tunnel($tunnel, 60);
153 die "no reply\n" if !$helo;
154 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
155 die "got strange reply from mtunnel ('$helo')\n"
156 if $helo !~ m/^tunnel online$/;
161 my $ver = $self->read_tunnel($tunnel, 10);
162 if ($ver =~ /^ver (\d+)$/) {
163 $tunnel->{version
} = $1;
164 $self->log('info', "ssh tunnel $ver\n");
166 $err = "received invalid tunnel version string '$ver'\n" if !$err;
171 $self->finish_command_pipe($tunnel);
172 die "can't open migration tunnel - $err";
178 my ($self, $tunnel) = @_;
180 eval { $self->write_tunnel($tunnel, 30, 'quit'); };
183 $self->finish_command_pipe($tunnel, 30);
185 if ($tunnel->{sock_addr
}) {
186 # ssh does not clean up on local host
187 my $cmd = ['rm', '-f', $tunnel->{sock_addr
}]; #
188 PVE
::Tools
::run_command
($cmd);
190 # .. and just to be sure check on remote side
191 unshift @{$cmd}, @{$self->{rem_ssh
}};
192 PVE
::Tools
::run_command
($cmd);
199 my ($self, $vmid, $code, @param) = @_;
201 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
205 my ($self, $vmid) = @_;
207 my $online = $self->{opts
}->{online
};
209 $self->{storecfg
} = PVE
::Storage
::config
();
212 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
214 PVE
::QemuConfig-
>check_lock($conf);
217 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
218 die "can't migrate running VM without --online\n" if !$online;
221 $self->{forcemachine
} = PVE
::QemuServer
::Machine
::qemu_machine_pxe
($vmid, $conf);
224 my $loc_res = PVE
::QemuServer
::check_local_resources
($conf, 1);
225 if (scalar @$loc_res) {
226 if ($self->{running
} || !$self->{opts
}->{force
}) {
227 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
229 $self->log('info', "migrating VM which uses local devices");
233 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
235 my $need_activate = [];
236 foreach my $volid (@$vollist) {
237 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
239 # check if storage is available on both nodes
240 my $targetsid = $self->{opts
}->{targetstorage
} // $sid;
242 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
243 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
245 if ($scfg->{shared
}) {
246 # PVE::Storage::activate_storage checks this for non-shared storages
247 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
248 warn "Used shared storage '$sid' is not online on source node!\n"
249 if !$plugin->check_connection($sid, $scfg);
251 # only activate if not shared
252 next if ($volid =~ m/vm-\d+-cloudinit/);
253 push @$need_activate, $volid;
258 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
260 # test ssh connection
261 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
262 eval { $self->cmd_quiet($cmd); };
263 die "Can't connect to destination address using public key\n" if $@;
269 my ($self, $vmid) = @_;
271 my $conf = $self->{vmconf
};
273 # local volumes which have been copied
274 $self->{volumes
} = [];
276 my $override_targetsid = $self->{opts
}->{targetstorage
};
280 # found local volumes and their origin
281 my $local_volumes = {};
282 my $local_volumes_errors = {};
283 my $other_errors = [];
286 my $log_error = sub {
287 my ($msg, $volid) = @_;
289 if (defined($volid)) {
290 $local_volumes_errors->{$volid} = $msg;
292 push @$other_errors, $msg;
297 my @sids = PVE
::Storage
::storage_ids
($self->{storecfg
});
298 foreach my $storeid (@sids) {
299 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $storeid);
300 next if $scfg->{shared
};
301 next if !PVE
::Storage
::storage_check_enabled
($self->{storecfg
}, $storeid, undef, 1);
303 # get list from PVE::Storage (for unused volumes)
304 my $dl = PVE
::Storage
::vdisk_list
($self->{storecfg
}, $storeid, $vmid);
306 next if @{$dl->{$storeid}} == 0;
308 my $targetsid = $override_targetsid // $storeid;
310 # check if storage is available on target node
311 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
313 PVE
::Storage
::foreach_volid
($dl, sub {
314 my ($volid, $sid, $volinfo) = @_;
316 $local_volumes->{$volid}->{ref} = 'storage';
318 # If with_snapshots is not set for storage migrate, it tries to use
319 # a raw+size stream, but on-the-fly conversion from qcow2 to raw+size
320 # back to qcow2 is currently not possible.
321 $local_volumes->{$volid}->{snapshots
} = ($volinfo->{format
} =~ /^(?:qcow2|vmdk)$/);
322 $local_volumes->{$volid}->{format
} = $volinfo->{format
};
326 my $test_volid = sub {
327 my ($volid, $attr) = @_;
329 if ($volid =~ m
|^/|) {
330 return if $attr->{shared
};
331 $local_volumes->{$volid}->{ref} = 'config';
332 die "local file/device\n";
335 my $snaprefs = $attr->{referenced_in_snapshot
};
337 if ($attr->{cdrom
}) {
338 if ($volid eq 'cdrom') {
339 my $msg = "can't migrate local cdrom drive";
340 if (defined($snaprefs) && !$attr->{referenced_in_config
}) {
341 my $snapnames = join(', ', sort keys %$snaprefs);
342 $msg .= " (referenced in snapshot - $snapnames)";
344 &$log_error("$msg\n");
347 return if $volid eq 'none';
350 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
352 my $targetsid = $override_targetsid // $sid;
353 # check if storage is available on both nodes
354 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
355 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
357 return if $scfg->{shared
};
359 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config
} ?
'config' : 'snapshot';
361 if ($attr->{cdrom
}) {
362 if ($volid =~ /vm-\d+-cloudinit/) {
363 $local_volumes->{$volid}->{ref} = 'generated';
366 die "local cdrom image\n";
369 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
371 die "owned by other VM (owner = VM $owner)\n"
372 if !$owner || ($owner != $self->{vmid
});
374 if (defined($snaprefs)) {
375 $local_volumes->{$volid}->{snapshots
} = 1;
377 # we cannot migrate shapshots on local storage
378 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
380 die "online storage migration not possible if snapshot exists\n" if $self->{running
};
381 if (!($scfg->{type
} eq 'zfspool' || $local_volumes->{$volid}->{format
} eq 'qcow2')) {
382 die "non-migratable snapshot exists\n";
386 die "referenced by linked clone(s)\n"
387 if PVE
::Storage
::volume_is_base_and_used
($self->{storecfg
}, $volid);
390 PVE
::QemuServer
::foreach_volid
($conf, sub {
391 my ($volid, $attr) = @_;
392 eval { $test_volid->($volid, $attr); };
394 &$log_error($err, $volid);
398 foreach my $vol (sort keys %$local_volumes) {
399 my $ref = $local_volumes->{$vol}->{ref};
400 if ($ref eq 'storage') {
401 $self->log('info', "found local disk '$vol' (via storage)\n");
402 } elsif ($ref eq 'config') {
403 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
404 if $self->{running
} && !$self->{opts
}->{"with-local-disks"};
405 $self->log('info', "found local disk '$vol' (in current VM config)\n");
406 } elsif ($ref eq 'snapshot') {
407 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
408 } elsif ($ref eq 'generated') {
409 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
411 $self->log('info', "found local disk '$vol'\n");
415 foreach my $vol (sort keys %$local_volumes_errors) {
416 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
418 foreach my $err (@$other_errors) {
419 $self->log('warn', "$err");
423 die "can't migrate VM - check log\n";
426 # additional checks for local storage
427 foreach my $volid (keys %$local_volumes) {
428 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
429 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $sid);
431 my $migratable = $scfg->{type
} =~ /^(?:dir|zfspool|lvmthin|lvm)$/;
433 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
436 # image is a linked clone on local storage, se we can't migrate.
437 if (my $basename = (PVE
::Storage
::parse_volname
($self->{storecfg
}, $volid))[3]) {
438 die "can't migrate '$volid' as it's a clone of '$basename'";
442 my $rep_cfg = PVE
::ReplicationConfig-
>new();
443 if (my $jobcfg = $rep_cfg->find_local_replication_job($vmid, $self->{node
})) {
444 die "can't live migrate VM with replicated volumes\n" if $self->{running
};
445 $self->log('info', "replicating disk images");
446 my $start_time = time();
447 my $logfunc = sub { $self->log('info', shift) };
448 $self->{replicated_volumes
} = PVE
::Replication
::run_replication
(
449 'PVE::QemuConfig', $jobcfg, $start_time, $start_time, $logfunc);
452 # sizes in config have to be accurate for remote node to correctly
453 # allocate disks, rescan to be sure
454 my $volid_hash = PVE
::QemuServer
::scan_volids
($self->{storecfg
}, $vmid);
455 PVE
::QemuServer
::foreach_drive
($conf, sub {
456 my ($key, $drive) = @_;
457 my ($updated, $old_size, $new_size) = PVE
::QemuServer
::Drive
::update_disksize
($drive, $volid_hash);
458 if (defined($updated)) {
459 $conf->{$key} = PVE
::QemuServer
::print_drive
($updated);
460 $self->log('info', "size of disk '$updated->{file}' ($key) updated from $old_size to $new_size\n");
464 $self->log('info', "copying local disk images") if scalar(%$local_volumes);
466 foreach my $volid (keys %$local_volumes) {
467 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
468 my $targetsid = $override_targetsid // $sid;
469 my $ref = $local_volumes->{$volid}->{ref};
470 if ($self->{running
} && $ref eq 'config') {
471 push @{$self->{online_local_volumes
}}, $volid;
472 } elsif ($ref eq 'generated') {
473 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n" if $self->{running
};
474 # skip all generated volumes but queue them for deletion in phase3_cleanup
475 push @{$self->{volumes
}}, $volid;
478 next if $self->{replicated_volumes
}->{$volid};
479 push @{$self->{volumes
}}, $volid;
480 my $opts = $self->{opts
};
481 my $insecure = $opts->{migration_type
} eq 'insecure';
482 my $with_snapshots = $local_volumes->{$volid}->{snapshots
};
483 # use 'migrate' limit for transfer to other node
484 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migration', [$targetsid, $sid], $opts->{bwlimit
});
485 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
486 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
488 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{ssh_info
}, $targetsid,
489 undef, undef, undef, $bwlimit, $insecure, $with_snapshots);
493 die "Failed to sync data - $@" if $@;
496 sub cleanup_remotedisks
{
499 foreach my $target_drive (keys %{$self->{target_drive
}}) {
501 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{drivestr
});
502 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
});
504 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
506 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
508 $self->log('err', $err);
515 my ($self, $vmid) = @_;
517 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
519 my $conf = $self->{vmconf
};
521 # set migrate lock in config file
522 $conf->{lock} = 'migrate';
523 PVE
::QemuConfig-
>write_config($vmid, $conf);
525 sync_disks
($self, $vmid);
527 # sync_disks fixes disk sizes to match their actual size, write changes so
528 # target allocates correct volumes
529 PVE
::QemuConfig-
>write_config($vmid, $conf);
533 my ($self, $vmid, $err) = @_;
535 $self->log('info', "aborting phase 1 - cleanup resources");
537 my $conf = $self->{vmconf
};
538 delete $conf->{lock};
539 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
541 $self->log('err', $err);
544 if ($self->{volumes
}) {
545 foreach my $volid (@{$self->{volumes
}}) {
546 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
547 # fixme: try to remove ?
553 my ($self, $vmid) = @_;
555 my $conf = $self->{vmconf
};
557 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
561 my $ruri; # the whole migration dst. URI (protocol:address[:port])
562 my $nodename = PVE
::INotify
::nodename
();
564 ## start on remote node
565 my $cmd = [@{$self->{rem_ssh
}}];
568 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
569 my $res = mon_cmd
($vmid, 'query-spice');
570 $spice_ticket = $res->{ticket
};
573 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
575 my $migration_type = $self->{opts
}->{migration_type
};
577 push @$cmd, '--migration_type', $migration_type;
579 push @$cmd, '--migration_network', $self->{opts
}->{migration_network
}
580 if $self->{opts
}->{migration_network
};
582 if ($migration_type eq 'insecure') {
583 push @$cmd, '--stateuri', 'tcp';
585 push @$cmd, '--stateuri', 'unix';
588 if ($self->{forcemachine
}) {
589 push @$cmd, '--machine', $self->{forcemachine
};
592 if ($self->{online_local_volumes
}) {
593 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
598 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
599 # instead we pipe it through STDIN
600 my $exitcode = PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
603 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
606 $ruri = "tcp:$raddr:$rport";
608 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
610 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
611 $ruri = "unix:$raddr";
613 elsif ($line =~ m/^migration listens on port (\d+)$/) {
614 $raddr = "localhost";
616 $ruri = "tcp:$raddr:$rport";
618 elsif ($line =~ m/^spice listens on port (\d+)$/) {
619 $spice_port = int($1);
621 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
623 my $nbd_uri = "nbd:$1:$2:exportname=$3";
624 my $targetdrive = $3;
625 $targetdrive =~ s/drive-//g;
627 $self->{target_drive
}->{$targetdrive}->{drivestr
} = $drivestr;
628 $self->{target_drive
}->{$targetdrive}->{nbd_uri
} = $nbd_uri;
630 } elsif ($line =~ m/^QEMU: (.*)$/) {
631 $self->log('info', "[$self->{node}] $1\n");
635 $self->log('info', "[$self->{node}] $line");
638 die "remote command failed with exit code $exitcode\n" if $exitcode;
640 die "unable to detect remote migration address\n" if !$raddr;
642 $self->log('info', "start remote tunnel");
644 if ($migration_type eq 'secure') {
646 if ($ruri =~ /^unix:/) {
648 $self->{tunnel
} = $self->fork_tunnel("$raddr:$raddr");
649 $self->{tunnel
}->{sock_addr
} = $raddr;
651 my $unix_socket_try = 0; # wait for the socket to become ready
652 while (! -S
$raddr) {
654 if ($unix_socket_try > 100) {
656 $self->finish_tunnel($self->{tunnel
});
657 die "Timeout, migration socket $ruri did not get ready";
663 } elsif ($ruri =~ /^tcp:/) {
665 if ($raddr eq "localhost") {
666 # for backwards compatibility with older qemu-server versions
667 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
668 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
669 $tunnel_addr = "$lport:localhost:$rport";
672 $self->{tunnel
} = $self->fork_tunnel($tunnel_addr);
675 die "unsupported protocol in migration URI: $ruri\n";
678 #fork tunnel for insecure migration, to send faster commands like resume
679 $self->{tunnel
} = $self->fork_tunnel();
684 my $opt_bwlimit = $self->{opts
}->{bwlimit
};
686 if (defined($self->{online_local_volumes
})) {
687 $self->{storage_migration
} = 1;
688 $self->{storage_migration_jobs
} = {};
689 $self->log('info', "starting storage migration");
691 die "The number of local disks does not match between the source and the destination.\n"
692 if (scalar(keys %{$self->{target_drive
}}) != scalar @{$self->{online_local_volumes
}});
693 foreach my $drive (keys %{$self->{target_drive
}}){
694 my $target = $self->{target_drive
}->{$drive};
695 my $nbd_uri = $target->{nbd_uri
};
697 my $source_drive = PVE
::QemuServer
::parse_drive
($drive, $conf->{$drive});
698 my $target_drive = PVE
::QemuServer
::parse_drive
($drive, $target->{drivestr
});
700 my $source_sid = PVE
::Storage
::Plugin
::parse_volume_id
($source_drive->{file
});
701 my $target_sid = PVE
::Storage
::Plugin
::parse_volume_id
($target_drive->{file
});
703 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migration', [$source_sid, $target_sid], $opt_bwlimit);
705 $self->log('info', "$drive: start migration to $nbd_uri");
706 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 1, undef, $bwlimit);
710 $self->log('info', "starting online/live migration on $ruri");
711 $self->{livemigration
} = 1;
714 my $defaults = PVE
::QemuServer
::load_defaults
();
716 $self->log('info', "set migration_caps");
718 PVE
::QemuServer
::set_migration_caps
($vmid);
722 my $qemu_migrate_params = {};
724 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
725 # migrate_speed parameter in qm.conf - take the lower of the two.
726 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migration', undef, $opt_bwlimit) // 0;
727 my $migrate_speed = $conf->{migrate_speed
} // $bwlimit;
728 # migrate_speed is in MB/s, bwlimit in KB/s
729 $migrate_speed *= 1024;
731 $migrate_speed = ($bwlimit < $migrate_speed) ?
$bwlimit : $migrate_speed;
733 # always set migrate speed (overwrite kvm default of 32m) we set a very high
734 # default of 8192m which is basically unlimited
735 $migrate_speed ||= ($defaults->{migrate_speed
} || 8192) * 1024;
737 # qmp takes migrate_speed in B/s.
738 $migrate_speed *= 1024;
739 $self->log('info', "migration speed limit: $migrate_speed B/s");
740 $qemu_migrate_params->{'max-bandwidth'} = int($migrate_speed);
742 my $migrate_downtime = $defaults->{migrate_downtime
};
743 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
744 if (defined($migrate_downtime)) {
745 # migrate-set-parameters expects limit in ms
746 $migrate_downtime *= 1000;
747 $self->log('info', "migration downtime limit: $migrate_downtime ms");
748 $qemu_migrate_params->{'downtime-limit'} = int($migrate_downtime);
751 # set cachesize to 10% of the total memory
752 my $memory = $conf->{memory
} || $defaults->{memory
};
753 my $cachesize = int($memory * 1048576 / 10);
754 $cachesize = round_powerof2
($cachesize);
756 $self->log('info', "migration cachesize: $cachesize B");
757 $qemu_migrate_params->{'xbzrle-cache-size'} = int($cachesize);
759 $self->log('info', "set migration parameters");
761 mon_cmd
($vmid, "migrate-set-parameters", %{$qemu_migrate_params});
763 $self->log('info', "migrate-set-parameters error: $@") if $@;
765 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
766 my $rpcenv = PVE
::RPCEnvironment
::get
();
767 my $authuser = $rpcenv->get_user();
769 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
771 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
772 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
774 $self->log('info', "spice client_migrate_info");
777 mon_cmd
($vmid, "client_migrate_info", protocol
=> 'spice',
778 hostname
=> $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
779 'cert-subject' => $subject);
781 $self->log('info', "client_migrate_info error: $@") if $@;
785 $self->log('info', "start migrate command to $ruri");
787 mon_cmd
($vmid, "migrate", uri
=> $ruri);
790 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
793 my $usleep = 1000000;
797 my $downtimecounter = 0;
800 my $avglstat = $lstat/$i if $lstat;
805 $stat = mon_cmd
($vmid, "query-migrate");
809 warn "query migrate failed: $err\n";
810 $self->log('info', "query migrate failed: $err");
811 if ($err_count <= 5) {
815 die "too many query migrate failures - aborting\n";
818 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(setup)$/im) {
823 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
826 if ($stat->{status
} eq 'completed') {
827 my $delay = time() - $start;
829 my $mbps = sprintf "%.2f", $memory / $delay;
830 my $downtime = $stat->{downtime
} || 0;
831 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
835 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
836 $self->log('info', "migration status error: $stat->{status}");
840 if ($stat->{status
} ne 'active') {
841 $self->log('info', "migration status: $stat->{status}");
845 if ($stat->{ram
}->{transferred
} ne $lstat) {
846 my $trans = $stat->{ram
}->{transferred
} || 0;
847 my $rem = $stat->{ram
}->{remaining
} || 0;
848 my $total = $stat->{ram
}->{total
} || 0;
849 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
850 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
851 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
852 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
853 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
854 # reduce sleep if remainig memory is lower than the average transfer speed
855 $usleep = 100000 if $avglstat && $rem < $avglstat;
857 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
858 "remaining ${rem}), total ${total})");
860 if (${xbzrlecachesize
}) {
861 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
864 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
869 if ($downtimecounter > 5) {
870 $downtimecounter = 0;
871 $migrate_downtime *= 2;
872 $self->log('info', "migrate_set_downtime: $migrate_downtime");
874 mon_cmd
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
876 $self->log('info', "migrate_set_downtime error: $@") if $@;
882 $lstat = $stat->{ram
}->{transferred
};
886 die "unable to parse migration status '$stat->{status}' - aborting\n";
892 my ($self, $vmid, $err) = @_;
894 return if !$self->{errors
};
895 $self->{phase2errors
} = 1;
897 $self->log('info', "aborting phase 2 - cleanup resources");
899 $self->log('info', "migrate_cancel");
901 mon_cmd
($vmid, "migrate_cancel");
903 $self->log('info', "migrate_cancel error: $@") if $@;
905 my $conf = $self->{vmconf
};
906 delete $conf->{lock};
907 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
909 $self->log('err', $err);
912 # cleanup ressources on target host
913 if ($self->{storage_migration
}) {
915 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
917 $self->log('err', $err);
920 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
922 $self->log('err', $err);
926 my $nodename = PVE
::INotify
::nodename
();
928 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
929 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
931 $self->log('err', $err);
935 if ($self->{tunnel
}) {
936 eval { finish_tunnel
($self, $self->{tunnel
}); };
938 $self->log('err', $err);
945 my ($self, $vmid) = @_;
947 my $volids = $self->{volumes
};
948 return if $self->{phase2errors
};
950 # destroy local copies
951 foreach my $volid (@$volids) {
952 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
954 $self->log('err', "removing local copy of '$volid' failed - $err");
956 last if $err =~ /^interrupted by signal$/;
962 my ($self, $vmid, $err) = @_;
964 my $conf = $self->{vmconf
};
965 return if $self->{phase2errors
};
967 my $tunnel = $self->{tunnel
};
969 if ($self->{storage_migration
}) {
971 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}); };
974 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
975 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
976 die "Failed to complete storage migration: $err\n";
978 foreach my $target_drive (keys %{$self->{target_drive
}}) {
979 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{drivestr
});
980 $conf->{$target_drive} = PVE
::QemuServer
::print_drive
($drive);
981 PVE
::QemuConfig-
>write_config($vmid, $conf);
986 # transfer replication state before move config
987 $self->transfer_replication_state() if $self->{replicated_volumes
};
989 # move config to remote node
990 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
991 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
993 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
994 if !rename($conffile, $newconffile);
996 $self->switch_replication_job_target() if $self->{replicated_volumes
};
998 if ($self->{livemigration
}) {
999 if ($self->{storage_migration
}) {
1000 # stop nbd server on remote vm - requirement for resume since 2.9
1001 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
1003 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1005 $self->log('err', $err);
1006 $self->{errors
} = 1;
1010 # config moved and nbd server stopped - now we can resume vm on target
1011 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
1013 $self->write_tunnel($tunnel, 30, "resume $vmid");
1016 $self->log('err', $err);
1017 $self->{errors
} = 1;
1020 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1023 $self->log('err', $line);
1025 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
1027 $self->log('err', $err);
1028 $self->{errors
} = 1;
1032 if ($self->{storage_migration
} && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
} && $self->{running
}) {
1033 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1034 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1038 # close tunnel on successful migration, on error phase2_cleanup closed it
1040 eval { finish_tunnel
($self, $tunnel); };
1042 $self->log('err', $err);
1043 $self->{errors
} = 1;
1049 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
1050 $self->log('info', "Waiting for spice server migration");
1052 my $res = mon_cmd
($vmid, 'query-spice');
1053 last if int($res->{'migrated'}) == 1;
1054 last if $timer > 50;
1061 # always stop local VM
1062 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
1064 $self->log('err', "stopping vm failed - $err");
1065 $self->{errors
} = 1;
1068 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1070 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1071 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
1074 $self->log('err', $err);
1075 $self->{errors
} = 1;
1078 if($self->{storage_migration
}) {
1079 # destroy local copies
1080 my $volids = $self->{online_local_volumes
};
1082 foreach my $volid (@$volids) {
1083 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1085 $self->log('err', "removing local copy of '$volid' failed - $err");
1086 $self->{errors
} = 1;
1087 last if $err =~ /^interrupted by signal$/;
1093 # clear migrate lock
1094 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1095 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1099 my ($self, $vmid) = @_;
1104 sub round_powerof2
{
1105 return 1 if $_[0] < 2;
1106 return 2 << int(log($_[0]-1)/log(2));