1 package PVE
::QemuMigrate
;
5 use PVE
::AbstractMigrate
;
8 use POSIX
qw( WNOHANG );
14 use Time
::HiRes
qw( usleep );
15 use PVE
::RPCEnvironment
;
16 use PVE
::ReplicationConfig
;
17 use PVE
::ReplicationState
;
20 use base
qw(PVE::AbstractMigrate);
22 sub fork_command_pipe
{
23 my ($self, $cmd) = @_;
25 my $reader = IO
::File-
>new();
26 my $writer = IO
::File-
>new();
32 eval { $cpid = open2
($reader, $writer, @$cmd); };
37 if ($orig_pid != $$) {
38 $self->log('err', "can't fork command pipe\n");
45 return { writer
=> $writer, reader
=> $reader, pid
=> $cpid };
48 sub finish_command_pipe
{
49 my ($self, $cmdpipe, $timeout) = @_;
51 my $cpid = $cmdpipe->{pid
};
52 return if !defined($cpid);
54 my $writer = $cmdpipe->{writer
};
55 my $reader = $cmdpipe->{reader
};
60 my $collect_child_process = sub {
61 my $res = waitpid($cpid, WNOHANG
);
62 if (defined($res) && ($res == $cpid)) {
63 delete $cmdpipe->{cpid
};
71 for (my $i = 0; $i < $timeout; $i++) {
72 return if &$collect_child_process();
77 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
81 for (my $i = 0; $i < 10; $i++) {
82 return if &$collect_child_process();
86 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
90 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
91 if !&$collect_child_process();
95 my ($self, $tunnel, $timeout) = @_;
97 $timeout = 60 if !defined($timeout);
99 my $reader = $tunnel->{reader
};
103 PVE
::Tools
::run_with_timeout
($timeout, sub { $output = <$reader>; });
105 die "reading from tunnel failed: $@\n" if $@;
113 my ($self, $tunnel, $timeout, $command) = @_;
115 $timeout = 60 if !defined($timeout);
117 my $writer = $tunnel->{writer
};
120 PVE
::Tools
::run_with_timeout
($timeout, sub {
121 print $writer "$command\n";
125 die "writing to tunnel failed: $@\n" if $@;
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 $@;
134 die "tunnel replied '$res' to command '$command'\n";
140 my ($self, $tunnel_addr) = @_;
142 my @localtunnelinfo = defined($tunnel_addr) ?
('-L' , $tunnel_addr ) : ();
144 my $cmd = [@{$self->{rem_ssh
}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, '/usr/sbin/qm', 'mtunnel' ];
146 my $tunnel = $self->fork_command_pipe($cmd);
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$/;
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");
163 $err = "received invalid tunnel version string '$ver'\n" if !$err;
168 $self->finish_command_pipe($tunnel);
169 die "can't open migration tunnel - $err";
175 my ($self, $tunnel) = @_;
177 eval { $self->write_tunnel($tunnel, 30, 'quit'); };
180 $self->finish_command_pipe($tunnel, 30);
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);
187 # .. and just to be sure check on remote side
188 unshift @{$cmd}, @{$self->{rem_ssh
}};
189 PVE
::Tools
::run_command
($cmd);
196 my ($self, $vmid, $code, @param) = @_;
198 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
202 my ($self, $vmid) = @_;
204 my $online = $self->{opts
}->{online
};
206 $self->{storecfg
} = PVE
::Storage
::config
();
209 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
211 PVE
::QemuConfig-
>check_lock($conf);
214 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
215 die "can't migrate running VM without --online\n" if !$online;
218 $self->{forcemachine
} = PVE
::QemuServer
::qemu_machine_pxe
($vmid, $conf);
221 my $loc_res = PVE
::QemuServer
::check_local_resources
($conf, 1);
222 if (scalar @$loc_res) {
223 if ($self->{running
} || !$self->{opts
}->{force
}) {
224 die "can't migrate VM which uses local devices: " . join(", ", @$loc_res) . "\n";
226 $self->log('info', "migrating VM which uses local devices");
230 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
232 my $need_activate = [];
233 foreach my $volid (@$vollist) {
234 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
236 # check if storage is available on both nodes
237 my $targetsid = $self->{opts
}->{targetstorage
} // $sid;
239 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
240 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
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);
248 # only activate if not shared
249 next if ($volid =~ m/vm-\d+-cloudinit/);
250 push @$need_activate, $volid;
255 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
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 $@;
266 my ($self, $vmid) = @_;
268 my $conf = $self->{vmconf
};
270 # local volumes which have been copied
271 $self->{volumes
} = [];
273 my $override_targetsid = $self->{opts
}->{targetstorage
};
277 # found local volumes and their origin
278 my $local_volumes = {};
279 my $local_volumes_errors = {};
280 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
});
311 $sharedvm = 0; # there is a non-shared disk
313 PVE
::Storage
::foreach_volid
($dl, sub {
314 my ($volid, $sid, $volname) = @_;
316 $local_volumes->{$volid}->{ref} = 'storage';
320 my $test_volid = sub {
321 my ($volid, $attr) = @_;
323 if ($volid =~ m
|^/|) {
324 return if $attr->{shared
};
325 $local_volumes->{$volid}->{ref} = 'config';
326 die "local file/device\n";
329 my $snaprefs = $attr->{referenced_in_snapshot
};
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)";
338 &$log_error("$msg\n");
341 return if $volid eq 'none';
344 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
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
});
351 return if $scfg->{shared
};
355 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config
} ?
'config' : 'snapshot';
357 if ($attr->{cdrom
}) {
358 if ($volid =~ /vm-\d+-cloudinit/) {
359 $local_volumes->{$volid}->{ref} = 'generated';
362 die "local cdrom image\n";
365 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
367 die "owned by other VM (owner = VM $owner)\n"
368 if !$owner || ($owner != $self->{vmid
});
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)
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";
382 die "referenced by linked clone(s)\n"
383 if PVE
::Storage
::volume_is_base_and_used
($self->{storecfg
}, $volid);
386 PVE
::QemuServer
::foreach_volid
($conf, sub {
387 my ($volid, $attr) = @_;
388 eval { $test_volid->($volid, $attr); };
390 &$log_error($err, $volid);
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");
407 $self->log('info', "found local disk '$vol'\n");
411 foreach my $vol (sort keys %$local_volumes_errors) {
412 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
414 foreach my $err (@$other_errors) {
415 $self->log('warn', "$err");
419 die "can't migrate VM - check log\n";
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);
427 my $migratable = ($scfg->{type
} eq 'dir') || ($scfg->{type
} eq 'zfspool') ||
428 ($scfg->{type
} eq 'lvmthin') || ($scfg->{type
} eq 'lvm');
430 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
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'";
441 $self->log('info', "copying disk images");
443 my $rep_cfg = PVE
::ReplicationConfig-
>new();
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;
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 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n" if $self->{running
};
462 # skip all generated volumes but queue them for deletion in phase3_cleanup
463 push @{$self->{volumes
}}, $volid;
466 next if $rep_volumes->{$volid};
467 push @{$self->{volumes
}}, $volid;
468 my $opts = $self->{opts
};
469 my $insecure = $opts->{migration_type
} eq 'insecure';
470 my $with_snapshots = $local_volumes->{$volid}->{snapshots
};
471 # use 'migrate' limit for transfer to other node
472 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migrate', [$targetsid, $sid], $opts->{bwlimit
});
473 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
474 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
476 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{ssh_info
}, $targetsid,
477 undef, undef, undef, $bwlimit, $insecure, $with_snapshots);
481 die "Failed to sync data - $@" if $@;
484 sub cleanup_remotedisks
{
487 foreach my $target_drive (keys %{$self->{target_drive
}}) {
489 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{volid
});
490 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
});
492 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
494 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
496 $self->log('err', $err);
503 my ($self, $vmid) = @_;
505 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
507 my $conf = $self->{vmconf
};
509 # set migrate lock in config file
510 $conf->{lock} = 'migrate';
511 PVE
::QemuConfig-
>write_config($vmid, $conf);
513 sync_disks
($self, $vmid);
518 my ($self, $vmid, $err) = @_;
520 $self->log('info', "aborting phase 1 - cleanup resources");
522 my $conf = $self->{vmconf
};
523 delete $conf->{lock};
524 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
526 $self->log('err', $err);
529 if ($self->{volumes
}) {
530 foreach my $volid (@{$self->{volumes
}}) {
531 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
532 # fixme: try to remove ?
538 my ($self, $vmid) = @_;
540 my $conf = $self->{vmconf
};
542 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
546 my $ruri; # the whole migration dst. URI (protocol:address[:port])
547 my $nodename = PVE
::INotify
::nodename
();
549 ## start on remote node
550 my $cmd = [@{$self->{rem_ssh
}}];
553 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
554 my $res = PVE
::QemuServer
::vm_mon_cmd
($vmid, 'query-spice');
555 $spice_ticket = $res->{ticket
};
558 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
560 my $migration_type = $self->{opts
}->{migration_type
};
562 push @$cmd, '--migration_type', $migration_type;
564 push @$cmd, '--migration_network', $self->{opts
}->{migration_network
}
565 if $self->{opts
}->{migration_network
};
567 if ($migration_type eq 'insecure') {
568 push @$cmd, '--stateuri', 'tcp';
570 push @$cmd, '--stateuri', 'unix';
573 if ($self->{forcemachine
}) {
574 push @$cmd, '--machine', $self->{forcemachine
};
577 if ($self->{online_local_volumes
}) {
578 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
583 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
584 # instead we pipe it through STDIN
585 PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
588 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
591 $ruri = "tcp:$raddr:$rport";
593 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
595 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
596 $ruri = "unix:$raddr";
598 elsif ($line =~ m/^migration listens on port (\d+)$/) {
599 $raddr = "localhost";
601 $ruri = "tcp:$raddr:$rport";
603 elsif ($line =~ m/^spice listens on port (\d+)$/) {
604 $spice_port = int($1);
606 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
608 my $nbd_uri = "nbd:$1:$2:exportname=$3";
609 my $targetdrive = $3;
610 $targetdrive =~ s/drive-//g;
612 $self->{target_drive
}->{$targetdrive}->{volid
} = $volid;
613 $self->{target_drive
}->{$targetdrive}->{nbd_uri
} = $nbd_uri;
618 $self->log('info', $line);
621 die "unable to detect remote migration address\n" if !$raddr;
623 $self->log('info', "start remote tunnel");
625 if ($migration_type eq 'secure') {
627 if ($ruri =~ /^unix:/) {
629 $self->{tunnel
} = $self->fork_tunnel("$raddr:$raddr");
630 $self->{tunnel
}->{sock_addr
} = $raddr;
632 my $unix_socket_try = 0; # wait for the socket to become ready
633 while (! -S
$raddr) {
635 if ($unix_socket_try > 100) {
637 $self->finish_tunnel($self->{tunnel
});
638 die "Timeout, migration socket $ruri did not get ready";
644 } elsif ($ruri =~ /^tcp:/) {
646 if ($raddr eq "localhost") {
647 # for backwards compatibility with older qemu-server versions
648 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
649 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
650 $tunnel_addr = "$lport:localhost:$rport";
653 $self->{tunnel
} = $self->fork_tunnel($tunnel_addr);
656 die "unsupported protocol in migration URI: $ruri\n";
659 #fork tunnel for insecure migration, to send faster commands like resume
660 $self->{tunnel
} = $self->fork_tunnel();
665 my $opt_bwlimit = $self->{opts
}->{bwlimit
};
667 if (defined($self->{online_local_volumes
})) {
668 $self->{storage_migration
} = 1;
669 $self->{storage_migration_jobs
} = {};
670 $self->log('info', "starting storage migration");
672 die "The number of local disks does not match between the source and the destination.\n"
673 if (scalar(keys %{$self->{target_drive
}}) != scalar @{$self->{online_local_volumes
}});
674 foreach my $drive (keys %{$self->{target_drive
}}){
675 my $target = $self->{target_drive
}->{$drive};
676 my $nbd_uri = $target->{nbd_uri
};
677 my $source_sid = PVE
::Storage
::Plugin
::parse_volume_id
($conf->{$drive});
678 my $target_sid = PVE
::Storage
::Plugin
::parse_volume_id
($target->{volid
});
679 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migrate', [$source_sid, $target_sid], $opt_bwlimit);
681 $self->log('info', "$drive: start migration to $nbd_uri");
682 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 1, undef, $bwlimit);
686 $self->log('info', "starting online/live migration on $ruri");
687 $self->{livemigration
} = 1;
690 my $defaults = PVE
::QemuServer
::load_defaults
();
692 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
693 # migrate_speed parameter in qm.conf - take the lower of the two.
694 my $bwlimit = PVE
::Storage
::get_bandwidth_limit
('migrate', undef, $opt_bwlimit) // 0;
695 my $migrate_speed = $conf->{migrate_speed
} // $bwlimit;
696 # migrate_speed is in MB/s, bwlimit in KB/s
697 $migrate_speed *= 1024;
699 $migrate_speed = ($bwlimit < $migrate_speed) ?
$bwlimit : $migrate_speed;
701 # always set migrate speed (overwrite kvm default of 32m) we set a very high
702 # default of 8192m which is basically unlimited
703 $migrate_speed ||= ($defaults->{migrate_speed
} || 8192) * 1024;
705 # qmp takes migrate_speed in B/s.
706 $migrate_speed *= 1024;
707 $self->log('info', "migrate_set_speed: $migrate_speed");
709 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_speed", value
=> int($migrate_speed));
711 $self->log('info', "migrate_set_speed error: $@") if $@;
713 my $migrate_downtime = $defaults->{migrate_downtime
};
714 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
715 if (defined($migrate_downtime)) {
716 $self->log('info', "migrate_set_downtime: $migrate_downtime");
718 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
720 $self->log('info', "migrate_set_downtime error: $@") if $@;
723 $self->log('info', "set migration_caps");
725 PVE
::QemuServer
::set_migration_caps
($vmid);
729 # set cachesize to 10% of the total memory
730 my $memory = $conf->{memory
} || $defaults->{memory
};
731 my $cachesize = int($memory * 1048576 / 10);
732 $cachesize = round_powerof2
($cachesize);
734 $self->log('info', "set cachesize: $cachesize");
736 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate-set-cache-size", value
=> int($cachesize));
738 $self->log('info', "migrate-set-cache-size error: $@") if $@;
740 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
741 my $rpcenv = PVE
::RPCEnvironment
::get
();
742 my $authuser = $rpcenv->get_user();
744 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
746 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
747 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
749 $self->log('info', "spice client_migrate_info");
752 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "client_migrate_info", protocol
=> 'spice',
753 hostname
=> $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
754 'cert-subject' => $subject);
756 $self->log('info', "client_migrate_info error: $@") if $@;
760 $self->log('info', "start migrate command to $ruri");
762 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate", uri
=> $ruri);
765 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
768 my $usleep = 1000000;
772 my $downtimecounter = 0;
775 my $avglstat = $lstat/$i if $lstat;
780 $stat = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "query-migrate");
784 warn "query migrate failed: $err\n";
785 $self->log('info', "query migrate failed: $err");
786 if ($err_count <= 5) {
790 die "too many query migrate failures - aborting\n";
793 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(setup)$/im) {
798 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
801 if ($stat->{status
} eq 'completed') {
802 my $delay = time() - $start;
804 my $mbps = sprintf "%.2f", $memory / $delay;
805 my $downtime = $stat->{downtime
} || 0;
806 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
810 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
811 $self->log('info', "migration status error: $stat->{status}");
815 if ($stat->{status
} ne 'active') {
816 $self->log('info', "migration status: $stat->{status}");
820 if ($stat->{ram
}->{transferred
} ne $lstat) {
821 my $trans = $stat->{ram
}->{transferred
} || 0;
822 my $rem = $stat->{ram
}->{remaining
} || 0;
823 my $total = $stat->{ram
}->{total
} || 0;
824 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
825 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
826 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
827 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
828 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
829 # reduce sleep if remainig memory is lower than the average transfer speed
830 $usleep = 100000 if $avglstat && $rem < $avglstat;
832 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
833 "remaining ${rem}), total ${total})");
835 if (${xbzrlecachesize
}) {
836 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
839 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
844 if ($downtimecounter > 5) {
845 $downtimecounter = 0;
846 $migrate_downtime *= 2;
847 $self->log('info', "migrate_set_downtime: $migrate_downtime");
849 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
851 $self->log('info', "migrate_set_downtime error: $@") if $@;
857 $lstat = $stat->{ram
}->{transferred
};
861 die "unable to parse migration status '$stat->{status}' - aborting\n";
867 my ($self, $vmid, $err) = @_;
869 return if !$self->{errors
};
870 $self->{phase2errors
} = 1;
872 $self->log('info', "aborting phase 2 - cleanup resources");
874 $self->log('info', "migrate_cancel");
876 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_cancel");
878 $self->log('info', "migrate_cancel error: $@") if $@;
880 my $conf = $self->{vmconf
};
881 delete $conf->{lock};
882 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
884 $self->log('err', $err);
887 # cleanup ressources on target host
888 if ($self->{storage_migration
}) {
890 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
892 $self->log('err', $err);
895 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
897 $self->log('err', $err);
901 my $nodename = PVE
::INotify
::nodename
();
903 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
904 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
906 $self->log('err', $err);
910 if ($self->{tunnel
}) {
911 eval { finish_tunnel
($self, $self->{tunnel
}); };
913 $self->log('err', $err);
920 my ($self, $vmid) = @_;
922 my $volids = $self->{volumes
};
923 return if $self->{phase2errors
};
925 # destroy local copies
926 foreach my $volid (@$volids) {
927 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
929 $self->log('err', "removing local copy of '$volid' failed - $err");
931 last if $err =~ /^interrupted by signal$/;
937 my ($self, $vmid, $err) = @_;
939 my $conf = $self->{vmconf
};
940 return if $self->{phase2errors
};
942 my $tunnel = $self->{tunnel
};
944 if ($self->{storage_migration
}) {
946 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}); };
949 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
950 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
951 die "Failed to completed storage migration\n";
953 foreach my $target_drive (keys %{$self->{target_drive
}}) {
954 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{volid
});
955 $conf->{$target_drive} = PVE
::QemuServer
::print_drive
($vmid, $drive);
956 PVE
::QemuConfig-
>write_config($vmid, $conf);
961 # transfer replication state before move config
962 $self->transfer_replication_state() if $self->{replicated_volumes
};
964 # move config to remote node
965 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
966 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
968 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
969 if !rename($conffile, $newconffile);
971 $self->switch_replication_job_target() if $self->{replicated_volumes
};
973 if ($self->{livemigration
}) {
974 if ($self->{storage_migration
}) {
975 # stop nbd server on remote vm - requirement for resume since 2.9
976 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
978 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
980 $self->log('err', $err);
985 # config moved and nbd server stopped - now we can resume vm on target
986 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
988 $self->write_tunnel($tunnel, 30, "resume $vmid");
991 $self->log('err', $err);
995 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
998 $self->log('err', $line);
1000 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
1002 $self->log('err', $err);
1003 $self->{errors
} = 1;
1007 if ($self->{storage_migration
} && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
} && $self->{running
}) {
1008 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1009 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
1013 # close tunnel on successful migration, on error phase2_cleanup closed it
1015 eval { finish_tunnel
($self, $tunnel); };
1017 $self->log('err', $err);
1018 $self->{errors
} = 1;
1024 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
1025 $self->log('info', "Waiting for spice server migration");
1027 my $res = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'query-spice');
1028 last if int($res->{'migrated'}) == 1;
1029 last if $timer > 50;
1036 # always stop local VM
1037 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
1039 $self->log('err', "stopping vm failed - $err");
1040 $self->{errors
} = 1;
1043 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1045 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1046 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
1049 $self->log('err', $err);
1050 $self->{errors
} = 1;
1053 if($self->{storage_migration
}) {
1054 # destroy local copies
1055 my $volids = $self->{online_local_volumes
};
1057 foreach my $volid (@$volids) {
1058 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1060 $self->log('err', "removing local copy of '$volid' failed - $err");
1061 $self->{errors
} = 1;
1062 last if $err =~ /^interrupted by signal$/;
1068 # clear migrate lock
1069 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1070 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1074 my ($self, $vmid) = @_;
1079 sub round_powerof2
{
1080 return 1 if $_[0] < 2;
1081 return 2 << int(log($_[0]-1)/log(2));