1 package PVE
::QemuMigrate
;
5 use PVE
::AbstractMigrate
;
8 use POSIX
qw( WNOHANG );
14 use PVE
::QemuServer
::Machine
;
15 use PVE
::QemuServer
::Monitor
qw(mon_cmd);
16 use Time
::HiRes
qw( usleep );
17 use PVE
::RPCEnvironment
;
18 use PVE
::ReplicationConfig
;
19 use PVE
::ReplicationState
;
22 use base
qw(PVE::AbstractMigrate);
24 sub fork_command_pipe
{
25 my ($self, $cmd) = @_;
27 my $reader = IO
::File-
>new();
28 my $writer = IO
::File-
>new();
34 eval { $cpid = open2
($reader, $writer, @$cmd); };
39 if ($orig_pid != $$) {
40 $self->log('err', "can't fork command pipe\n");
47 return { writer
=> $writer, reader
=> $reader, pid
=> $cpid };
50 sub finish_command_pipe
{
51 my ($self, $cmdpipe, $timeout) = @_;
53 my $cpid = $cmdpipe->{pid
};
54 return if !defined($cpid);
56 my $writer = $cmdpipe->{writer
};
57 my $reader = $cmdpipe->{reader
};
62 my $collect_child_process = sub {
63 my $res = waitpid($cpid, WNOHANG
);
64 if (defined($res) && ($res == $cpid)) {
65 delete $cmdpipe->{cpid
};
73 for (my $i = 0; $i < $timeout; $i++) {
74 return if &$collect_child_process();
79 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
83 for (my $i = 0; $i < 10; $i++) {
84 return if &$collect_child_process();
88 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
92 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
93 if !&$collect_child_process();
97 my ($self, $tunnel, $timeout) = @_;
99 $timeout = 60 if !defined($timeout);
101 my $reader = $tunnel->{reader
};
105 PVE
::Tools
::run_with_timeout
($timeout, sub { $output = <$reader>; });
107 die "reading from tunnel failed: $@\n" if $@;
115 my ($self, $tunnel, $timeout, $command) = @_;
117 $timeout = 60 if !defined($timeout);
119 my $writer = $tunnel->{writer
};
122 PVE
::Tools
::run_with_timeout
($timeout, sub {
123 print $writer "$command\n";
127 die "writing to tunnel failed: $@\n" if $@;
129 if ($tunnel->{version
} && $tunnel->{version
} >= 1) {
130 my $res = eval { $self->read_tunnel($tunnel, 10); };
131 die "no reply to command '$command': $@\n" if $@;
136 die "tunnel replied '$res' to command '$command'\n";
142 my ($self, $tunnel_addr) = @_;
144 my @localtunnelinfo = defined($tunnel_addr) ?
('-L' , $tunnel_addr ) : ();
146 my $cmd = [@{$self->{rem_ssh
}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, '/usr/sbin/qm', 'mtunnel' ];
148 my $tunnel = $self->fork_command_pipe($cmd);
151 my $helo = $self->read_tunnel($tunnel, 60);
152 die "no reply\n" if !$helo;
153 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
154 die "got strange reply from mtunnel ('$helo')\n"
155 if $helo !~ m/^tunnel online$/;
160 my $ver = $self->read_tunnel($tunnel, 10);
161 if ($ver =~ /^ver (\d+)$/) {
162 $tunnel->{version
} = $1;
163 $self->log('info', "ssh tunnel $ver\n");
165 $err = "received invalid tunnel version string '$ver'\n" if !$err;
170 $self->finish_command_pipe($tunnel);
171 die "can't open migration tunnel - $err";
177 my ($self, $tunnel) = @_;
179 eval { $self->write_tunnel($tunnel, 30, 'quit'); };
182 $self->finish_command_pipe($tunnel, 30);
184 if ($tunnel->{sock_addr
}) {
185 # ssh does not clean up on local host
186 my $cmd = ['rm', '-f', $tunnel->{sock_addr
}]; #
187 PVE
::Tools
::run_command
($cmd);
189 # .. and just to be sure check on remote side
190 unshift @{$cmd}, @{$self->{rem_ssh
}};
191 PVE
::Tools
::run_command
($cmd);
198 my ($self, $vmid, $code, @param) = @_;
200 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
204 my ($self, $vmid) = @_;
206 my $online = $self->{opts
}->{online
};
208 $self->{storecfg
} = PVE
::Storage
::config
();
211 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
213 PVE
::QemuConfig-
>check_lock($conf);
216 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
217 die "can't migrate running VM without --online\n" if !$online;
220 $self->{forcemachine
} = PVE
::QemuServer
::Machine
::qemu_machine_pxe
($vmid, $conf);
223 my $loc_res = PVE
::QemuServer
::check_local_resources
($conf, 1);
224 if (scalar @$loc_res) {
225 if ($self->{running
} || !$self->{opts
}->{force
}) {
226 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
228 $self->log('info', "migrating VM which uses local devices");
232 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
234 my $need_activate = [];
235 foreach my $volid (@$vollist) {
236 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
238 # check if storage is available on both nodes
239 my $targetsid = $self->{opts
}->{targetstorage
} // $sid;
241 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
242 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
244 if ($scfg->{shared
}) {
245 # PVE::Storage::activate_storage checks this for non-shared storages
246 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
247 warn "Used shared storage '$sid' is not online on source node!\n"
248 if !$plugin->check_connection($sid, $scfg);
250 # only activate if not shared
251 next if ($volid =~ m/vm-\d+-cloudinit/);
252 push @$need_activate, $volid;
257 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
259 # test ssh connection
260 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
261 eval { $self->cmd_quiet($cmd); };
262 die "Can't connect to destination address using public key\n" if $@;
268 my ($self, $vmid) = @_;
270 my $conf = $self->{vmconf
};
272 # local volumes which have been copied
273 $self->{volumes
} = [];
275 my $override_targetsid = $self->{opts
}->{targetstorage
};
279 # found local volumes and their origin
280 my $local_volumes = {};
281 my $local_volumes_errors = {};
282 my $other_errors = [];
285 my $log_error = sub {
286 my ($msg, $volid) = @_;
288 if (defined($volid)) {
289 $local_volumes_errors->{$volid} = $msg;
291 push @$other_errors, $msg;
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);
302 # get list from PVE::Storage (for unused volumes)
303 my $dl = PVE
::Storage
::vdisk_list
($self->{storecfg
}, $storeid, $vmid);
305 next if @{$dl->{$storeid}} == 0;
307 my $targetsid = $override_targetsid // $storeid;
309 # check if storage is available on target node
310 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
312 PVE
::Storage
::foreach_volid
($dl, sub {
313 my ($volid, $sid, $volname) = @_;
315 $local_volumes->{$volid}->{ref} = 'storage';
319 my $test_volid = sub {
320 my ($volid, $attr) = @_;
322 if ($volid =~ m
|^/|) {
323 return if $attr->{shared
};
324 $local_volumes->{$volid}->{ref} = 'config';
325 die "local file/device\n";
328 my $snaprefs = $attr->{referenced_in_snapshot
};
330 if ($attr->{cdrom
}) {
331 if ($volid eq 'cdrom') {
332 my $msg = "can't migrate local cdrom drive";
333 if (defined($snaprefs) && !$attr->{referenced_in_config
}) {
334 my $snapnames = join(', ', sort keys %$snaprefs);
335 $msg .= " (referenced in snapshot - $snapnames)";
337 &$log_error("$msg\n");
340 return if $volid eq 'none';
343 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
345 my $targetsid = $override_targetsid // $sid;
346 # check if storage is available on both nodes
347 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
348 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
350 return if $scfg->{shared
};
352 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config
} ?
'config' : 'snapshot';
354 if ($attr->{cdrom
}) {
355 if ($volid =~ /vm-\d+-cloudinit/) {
356 $local_volumes->{$volid}->{ref} = 'generated';
359 die "local cdrom image\n";
362 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
364 die "owned by other VM (owner = VM $owner)\n"
365 if !$owner || ($owner != $self->{vmid
});
367 my $format = PVE
::QemuServer
::qemu_img_format
($scfg, $volname);
368 $local_volumes->{$volid}->{snapshots
} = defined($snaprefs) || ($format =~ /^(?:qcow2|vmdk)$/);
369 if (defined($snaprefs)) {
370 # we cannot migrate shapshots on local storage
371 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
373 die "online storage migration not possible if snapshot exists\n" if $self->{running
};
374 if (!($scfg->{type
} eq 'zfspool' || $format eq 'qcow2')) {
375 die "non-migratable snapshot exists\n";
379 die "referenced by linked clone(s)\n"
380 if PVE
::Storage
::volume_is_base_and_used
($self->{storecfg
}, $volid);
383 PVE
::QemuServer
::foreach_volid
($conf, sub {
384 my ($volid, $attr) = @_;
385 eval { $test_volid->($volid, $attr); };
387 &$log_error($err, $volid);
391 foreach my $vol (sort keys %$local_volumes) {
392 my $ref = $local_volumes->{$vol}->{ref};
393 if ($ref eq 'storage') {
394 $self->log('info', "found local disk '$vol' (via storage)\n");
395 } elsif ($ref eq 'config') {
396 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
397 if $self->{running
} && !$self->{opts
}->{"with-local-disks"};
398 $self->log('info', "found local disk '$vol' (in current VM config)\n");
399 } elsif ($ref eq 'snapshot') {
400 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
401 } elsif ($ref eq 'generated') {
402 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
404 $self->log('info', "found local disk '$vol'\n");
408 foreach my $vol (sort keys %$local_volumes_errors) {
409 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
411 foreach my $err (@$other_errors) {
412 $self->log('warn', "$err");
416 die "can't migrate VM - check log\n";
419 # additional checks for local storage
420 foreach my $volid (keys %$local_volumes) {
421 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
422 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $sid);
424 my $migratable = $scfg->{type
} =~ /^(?:dir|zfspool|lvmthin|lvm)$/;
426 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
429 # image is a linked clone on local storage, se we can't migrate.
430 if (my $basename = (PVE
::Storage
::parse_volname
($self->{storecfg
}, $volid))[3]) {
431 die "can't migrate '$volid' as it's a clone of '$basename'";
435 my $rep_cfg = PVE
::ReplicationConfig-
>new();
436 if (my $jobcfg = $rep_cfg->find_local_replication_job($vmid, $self->{node
})) {
437 die "can't live migrate VM with replicated volumes\n" if $self->{running
};
438 $self->log('info', "replicating disk images");
439 my $start_time = time();
440 my $logfunc = sub { $self->log('info', shift) };
441 $self->{replicated_volumes
} = PVE
::Replication
::run_replication
(
442 'PVE::QemuConfig', $jobcfg, $start_time, $start_time, $logfunc);
445 # sizes in config have to be accurate for remote node to correctly
446 # allocate disks, rescan to be sure
447 my $volid_hash = PVE
::QemuServer
::scan_volids
($self->{storecfg
}, $vmid);
448 PVE
::QemuServer
::foreach_drive
($conf, sub {
449 my ($key, $drive) = @_;
450 my ($updated, $old_size, $new_size) = PVE
::QemuServer
::update_disksize
($drive, $volid_hash);
451 if (defined($updated)) {
452 $conf->{$key} = PVE
::QemuServer
::print_drive
($updated);
453 $self->log('info', "size of disk '$updated->{file}' ($key) updated from $old_size to $new_size\n");
457 $self->log('info', "copying local disk images") if scalar(%$local_volumes);
459 foreach my $volid (keys %$local_volumes) {
460 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
461 my $targetsid = $override_targetsid // $sid;
462 my $ref = $local_volumes->{$volid}->{ref};
463 if ($self->{running
} && $ref eq 'config') {
464 push @{$self->{online_local_volumes
}}, $volid;
465 } elsif ($ref eq 'generated') {
466 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n" if $self->{running
};
467 # skip all generated volumes but queue them for deletion in phase3_cleanup
468 push @{$self->{volumes
}}, $volid;
471 next if $self->{replicated_volumes
}->{$volid};
472 push @{$self->{volumes
}}, $volid;
473 my $opts = $self->{opts
};
474 my $insecure = $opts->{migration_type
} eq 'insecure';
475 my $with_snapshots = $local_volumes->{$volid}->{snapshots
};
476 # use 'migrate' limit for transfer to other node
477 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migrate', [$targetsid, $sid], $opts->{bwlimit
});
478 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
479 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
481 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{ssh_info
}, $targetsid,
482 undef, undef, undef, $bwlimit, $insecure, $with_snapshots);
486 die "Failed to sync data - $@" if $@;
489 sub cleanup_remotedisks
{
492 foreach my $target_drive (keys %{$self->{target_drive
}}) {
494 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{drivestr
});
495 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
});
497 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
499 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
501 $self->log('err', $err);
508 my ($self, $vmid) = @_;
510 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
512 my $conf = $self->{vmconf
};
514 # set migrate lock in config file
515 $conf->{lock} = 'migrate';
516 PVE
::QemuConfig-
>write_config($vmid, $conf);
518 sync_disks
($self, $vmid);
520 # sync_disks fixes disk sizes to match their actual size, write changes so
521 # target allocates correct volumes
522 PVE
::QemuConfig-
>write_config($vmid, $conf);
526 my ($self, $vmid, $err) = @_;
528 $self->log('info', "aborting phase 1 - cleanup resources");
530 my $conf = $self->{vmconf
};
531 delete $conf->{lock};
532 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
534 $self->log('err', $err);
537 if ($self->{volumes
}) {
538 foreach my $volid (@{$self->{volumes
}}) {
539 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
540 # fixme: try to remove ?
546 my ($self, $vmid) = @_;
548 my $conf = $self->{vmconf
};
550 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
554 my $ruri; # the whole migration dst. URI (protocol:address[:port])
555 my $nodename = PVE
::INotify
::nodename
();
557 ## start on remote node
558 my $cmd = [@{$self->{rem_ssh
}}];
561 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
562 my $res = mon_cmd
($vmid, 'query-spice');
563 $spice_ticket = $res->{ticket
};
566 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
568 my $migration_type = $self->{opts
}->{migration_type
};
570 push @$cmd, '--migration_type', $migration_type;
572 push @$cmd, '--migration_network', $self->{opts
}->{migration_network
}
573 if $self->{opts
}->{migration_network
};
575 if ($migration_type eq 'insecure') {
576 push @$cmd, '--stateuri', 'tcp';
578 push @$cmd, '--stateuri', 'unix';
581 if ($self->{forcemachine
}) {
582 push @$cmd, '--machine', $self->{forcemachine
};
585 if ($self->{online_local_volumes
}) {
586 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
591 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
592 # instead we pipe it through STDIN
593 my $exitcode = PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
596 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
599 $ruri = "tcp:$raddr:$rport";
601 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
603 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
604 $ruri = "unix:$raddr";
606 elsif ($line =~ m/^migration listens on port (\d+)$/) {
607 $raddr = "localhost";
609 $ruri = "tcp:$raddr:$rport";
611 elsif ($line =~ m/^spice listens on port (\d+)$/) {
612 $spice_port = int($1);
614 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
616 my $nbd_uri = "nbd:$1:$2:exportname=$3";
617 my $targetdrive = $3;
618 $targetdrive =~ s/drive-//g;
620 $self->{target_drive
}->{$targetdrive}->{drivestr
} = $drivestr;
621 $self->{target_drive
}->{$targetdrive}->{nbd_uri
} = $nbd_uri;
623 } elsif ($line =~ m/^QEMU: (.*)$/) {
624 $self->log('info', "[$self->{node}] $1\n");
628 $self->log('info', "[$self->{node}] $line");
631 die "remote command failed with exit code $exitcode\n" if $exitcode;
633 die "unable to detect remote migration address\n" if !$raddr;
635 $self->log('info', "start remote tunnel");
637 if ($migration_type eq 'secure') {
639 if ($ruri =~ /^unix:/) {
641 $self->{tunnel
} = $self->fork_tunnel("$raddr:$raddr");
642 $self->{tunnel
}->{sock_addr
} = $raddr;
644 my $unix_socket_try = 0; # wait for the socket to become ready
645 while (! -S
$raddr) {
647 if ($unix_socket_try > 100) {
649 $self->finish_tunnel($self->{tunnel
});
650 die "Timeout, migration socket $ruri did not get ready";
656 } elsif ($ruri =~ /^tcp:/) {
658 if ($raddr eq "localhost") {
659 # for backwards compatibility with older qemu-server versions
660 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
661 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
662 $tunnel_addr = "$lport:localhost:$rport";
665 $self->{tunnel
} = $self->fork_tunnel($tunnel_addr);
668 die "unsupported protocol in migration URI: $ruri\n";
671 #fork tunnel for insecure migration, to send faster commands like resume
672 $self->{tunnel
} = $self->fork_tunnel();
677 my $opt_bwlimit = $self->{opts
}->{bwlimit
};
679 if (defined($self->{online_local_volumes
})) {
680 $self->{storage_migration
} = 1;
681 $self->{storage_migration_jobs
} = {};
682 $self->log('info', "starting storage migration");
684 die "The number of local disks does not match between the source and the destination.\n"
685 if (scalar(keys %{$self->{target_drive
}}) != scalar @{$self->{online_local_volumes
}});
686 foreach my $drive (keys %{$self->{target_drive
}}){
687 my $target = $self->{target_drive
}->{$drive};
688 my $nbd_uri = $target->{nbd_uri
};
689 my $target_drive = PVE
::QemuServer
::parse_drive
($drive, $target->{drivestr
});
690 my $source_drive = PVE
::QemuServer
::parse_drive
($drive, $conf->{$drive});
691 my $source_sid = PVE
::Storage
::Plugin
::parse_volume_id
($source_drive->{file
});
692 my $target_sid = PVE
::Storage
::Plugin
::parse_volume_id
($target_drive->{file
});
693 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migrate', [$source_sid, $target_sid], $opt_bwlimit);
695 $self->log('info', "$drive: start migration to $nbd_uri");
696 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 1, undef, $bwlimit);
700 $self->log('info', "starting online/live migration on $ruri");
701 $self->{livemigration
} = 1;
704 my $defaults = PVE
::QemuServer
::load_defaults
();
706 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
707 # migrate_speed parameter in qm.conf - take the lower of the two.
708 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migrate', undef, $opt_bwlimit) // 0;
709 my $migrate_speed = $conf->{migrate_speed
} // $bwlimit;
710 # migrate_speed is in MB/s, bwlimit in KB/s
711 $migrate_speed *= 1024;
713 $migrate_speed = ($bwlimit < $migrate_speed) ?
$bwlimit : $migrate_speed;
715 # always set migrate speed (overwrite kvm default of 32m) we set a very high
716 # default of 8192m which is basically unlimited
717 $migrate_speed ||= ($defaults->{migrate_speed
} || 8192) * 1024;
719 # qmp takes migrate_speed in B/s.
720 $migrate_speed *= 1024;
721 $self->log('info', "migrate_set_speed: $migrate_speed");
723 mon_cmd
($vmid, "migrate_set_speed", value
=> int($migrate_speed));
725 $self->log('info', "migrate_set_speed error: $@") if $@;
727 my $migrate_downtime = $defaults->{migrate_downtime
};
728 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
729 if (defined($migrate_downtime)) {
730 $self->log('info', "migrate_set_downtime: $migrate_downtime");
732 mon_cmd
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
734 $self->log('info', "migrate_set_downtime error: $@") if $@;
737 $self->log('info', "set migration_caps");
739 PVE
::QemuServer
::set_migration_caps
($vmid);
743 # set cachesize to 10% of the total memory
744 my $memory = $conf->{memory
} || $defaults->{memory
};
745 my $cachesize = int($memory * 1048576 / 10);
746 $cachesize = round_powerof2
($cachesize);
748 $self->log('info', "set cachesize: $cachesize");
750 mon_cmd
($vmid, "migrate-set-cache-size", value
=> int($cachesize));
752 $self->log('info', "migrate-set-cache-size error: $@") if $@;
754 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
755 my $rpcenv = PVE
::RPCEnvironment
::get
();
756 my $authuser = $rpcenv->get_user();
758 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
760 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
761 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
763 $self->log('info', "spice client_migrate_info");
766 mon_cmd
($vmid, "client_migrate_info", protocol
=> 'spice',
767 hostname
=> $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
768 'cert-subject' => $subject);
770 $self->log('info', "client_migrate_info error: $@") if $@;
774 $self->log('info', "start migrate command to $ruri");
776 mon_cmd
($vmid, "migrate", uri
=> $ruri);
779 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
782 my $usleep = 1000000;
786 my $downtimecounter = 0;
789 my $avglstat = $lstat/$i if $lstat;
794 $stat = mon_cmd
($vmid, "query-migrate");
798 warn "query migrate failed: $err\n";
799 $self->log('info', "query migrate failed: $err");
800 if ($err_count <= 5) {
804 die "too many query migrate failures - aborting\n";
807 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(setup)$/im) {
812 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
815 if ($stat->{status
} eq 'completed') {
816 my $delay = time() - $start;
818 my $mbps = sprintf "%.2f", $memory / $delay;
819 my $downtime = $stat->{downtime
} || 0;
820 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
824 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
825 $self->log('info', "migration status error: $stat->{status}");
829 if ($stat->{status
} ne 'active') {
830 $self->log('info', "migration status: $stat->{status}");
834 if ($stat->{ram
}->{transferred
} ne $lstat) {
835 my $trans = $stat->{ram
}->{transferred
} || 0;
836 my $rem = $stat->{ram
}->{remaining
} || 0;
837 my $total = $stat->{ram
}->{total
} || 0;
838 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
839 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
840 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
841 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
842 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
843 # reduce sleep if remainig memory is lower than the average transfer speed
844 $usleep = 100000 if $avglstat && $rem < $avglstat;
846 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
847 "remaining ${rem}), total ${total})");
849 if (${xbzrlecachesize
}) {
850 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
853 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
858 if ($downtimecounter > 5) {
859 $downtimecounter = 0;
860 $migrate_downtime *= 2;
861 $self->log('info', "migrate_set_downtime: $migrate_downtime");
863 mon_cmd
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
865 $self->log('info', "migrate_set_downtime error: $@") if $@;
871 $lstat = $stat->{ram
}->{transferred
};
875 die "unable to parse migration status '$stat->{status}' - aborting\n";
881 my ($self, $vmid, $err) = @_;
883 return if !$self->{errors
};
884 $self->{phase2errors
} = 1;
886 $self->log('info', "aborting phase 2 - cleanup resources");
888 $self->log('info', "migrate_cancel");
890 mon_cmd
($vmid, "migrate_cancel");
892 $self->log('info', "migrate_cancel error: $@") if $@;
894 my $conf = $self->{vmconf
};
895 delete $conf->{lock};
896 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
898 $self->log('err', $err);
901 # cleanup ressources on target host
902 if ($self->{storage_migration
}) {
904 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
906 $self->log('err', $err);
909 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
911 $self->log('err', $err);
915 my $nodename = PVE
::INotify
::nodename
();
917 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
918 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
920 $self->log('err', $err);
924 if ($self->{tunnel
}) {
925 eval { finish_tunnel
($self, $self->{tunnel
}); };
927 $self->log('err', $err);
934 my ($self, $vmid) = @_;
936 my $volids = $self->{volumes
};
937 return if $self->{phase2errors
};
939 # destroy local copies
940 foreach my $volid (@$volids) {
941 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
943 $self->log('err', "removing local copy of '$volid' failed - $err");
945 last if $err =~ /^interrupted by signal$/;
951 my ($self, $vmid, $err) = @_;
953 my $conf = $self->{vmconf
};
954 return if $self->{phase2errors
};
956 my $tunnel = $self->{tunnel
};
958 if ($self->{storage_migration
}) {
960 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}); };
963 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
964 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
965 die "Failed to complete storage migration: $err\n";
967 foreach my $target_drive (keys %{$self->{target_drive
}}) {
968 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{drivestr
});
969 $conf->{$target_drive} = PVE
::QemuServer
::print_drive
($drive);
970 PVE
::QemuConfig-
>write_config($vmid, $conf);
975 # transfer replication state before move config
976 $self->transfer_replication_state() if $self->{replicated_volumes
};
978 # move config to remote node
979 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
980 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
982 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
983 if !rename($conffile, $newconffile);
985 $self->switch_replication_job_target() if $self->{replicated_volumes
};
987 if ($self->{livemigration
}) {
988 if ($self->{storage_migration
}) {
989 # stop nbd server on remote vm - requirement for resume since 2.9
990 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
992 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
994 $self->log('err', $err);
999 # config moved and nbd server stopped - now we can resume vm on target
1000 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
1002 $self->write_tunnel($tunnel, 30, "resume $vmid");
1005 $self->log('err', $err);
1006 $self->{errors
} = 1;
1009 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1012 $self->log('err', $line);
1014 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
1016 $self->log('err', $err);
1017 $self->{errors
} = 1;
1021 if ($self->{storage_migration
} && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
} && $self->{running
}) {
1022 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1023 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1027 # close tunnel on successful migration, on error phase2_cleanup closed it
1029 eval { finish_tunnel
($self, $tunnel); };
1031 $self->log('err', $err);
1032 $self->{errors
} = 1;
1038 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
1039 $self->log('info', "Waiting for spice server migration");
1041 my $res = mon_cmd
($vmid, 'query-spice');
1042 last if int($res->{'migrated'}) == 1;
1043 last if $timer > 50;
1050 # always stop local VM
1051 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
1053 $self->log('err', "stopping vm failed - $err");
1054 $self->{errors
} = 1;
1057 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1059 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1060 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
1063 $self->log('err', $err);
1064 $self->{errors
} = 1;
1067 if($self->{storage_migration
}) {
1068 # destroy local copies
1069 my $volids = $self->{online_local_volumes
};
1071 foreach my $volid (@$volids) {
1072 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1074 $self->log('err', "removing local copy of '$volid' failed - $err");
1075 $self->{errors
} = 1;
1076 last if $err =~ /^interrupted by signal$/;
1082 # clear migrate lock
1083 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1084 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1088 my ($self, $vmid) = @_;
1093 sub round_powerof2
{
1094 return 1 if $_[0] < 2;
1095 return 2 << int(log($_[0]-1)/log(2));