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);
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";
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
} ?
$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 push @$need_activate, $volid;
254 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
256 # test ssh connection
257 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
258 eval { $self->cmd_quiet($cmd); };
259 die "Can't connect to destination address using public key\n" if $@;
265 my ($self, $vmid) = @_;
267 my $conf = $self->{vmconf
};
269 # local volumes which have been copied
270 $self->{volumes
} = [];
274 # found local volumes and their origin
275 my $local_volumes = {};
276 my $local_volumes_errors = {};
277 my $other_errors = [];
282 my $log_error = sub {
283 my ($msg, $volid) = @_;
285 if (defined($volid)) {
286 $local_volumes_errors->{$volid} = $msg;
288 push @$other_errors, $msg;
293 my @sids = PVE
::Storage
::storage_ids
($self->{storecfg
});
294 foreach my $storeid (@sids) {
295 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $storeid);
296 next if $scfg->{shared
};
297 next if !PVE
::Storage
::storage_check_enabled
($self->{storecfg
}, $storeid, undef, 1);
299 # get list from PVE::Storage (for unused volumes)
300 my $dl = PVE
::Storage
::vdisk_list
($self->{storecfg
}, $storeid, $vmid);
302 next if @{$dl->{$storeid}} == 0;
304 my $targetsid = $self->{opts
}->{targetstorage
} ?
$self->{opts
}->{targetstorage
} : $storeid;
306 # check if storage is available on target node
307 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
308 $sharedvm = 0; # there is a non-shared disk
310 PVE
::Storage
::foreach_volid
($dl, sub {
311 my ($volid, $sid, $volname) = @_;
313 $local_volumes->{$volid}->{ref} = 'storage';
317 my $test_volid = sub {
318 my ($volid, $attr) = @_;
320 if ($volid =~ m
|^/|) {
321 return if $attr->{shared
};
322 $local_volumes->{$volid}->{ref} = 'config';
323 die "local file/device\n";
326 my $snaprefs = $attr->{referenced_in_snapshot
};
328 if ($attr->{cdrom
}) {
329 if ($volid eq 'cdrom') {
330 my $msg = "can't migrate local cdrom drive";
331 if (defined($snaprefs) && !$attr->{referenced_in_config
}) {
332 my $snapnames = join(', ', sort keys %$snaprefs);
333 $msg .= " (referenced in snapshot - $snapnames)";
335 &$log_error("$msg\n");
338 return if $volid eq 'none';
341 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
343 my $targetsid = $self->{opts
}->{targetstorage
} ?
$self->{opts
}->{targetstorage
} : $sid;
344 # check if storage is available on both nodes
345 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
346 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $targetsid, $self->{node
});
348 return if $scfg->{shared
};
352 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config
} ?
'config' : 'snapshot';
354 die "local cdrom image\n" if $attr->{cdrom
};
356 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
358 die "owned by other VM (owner = VM $owner)\n"
359 if !$owner || ($owner != $self->{vmid
});
361 my $format = PVE
::QemuServer
::qemu_img_format
($scfg, $volname);
362 $local_volumes->{$volid}->{snapshots
} = defined($snaprefs) || ($format =~ /^(?:qcow2|vmdk)$/);
363 if (defined($snaprefs)) {
364 # we cannot migrate shapshots on local storage
365 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
367 die "online storage migration not possible if snapshot exists\n" if $self->{running
};
368 if (!($scfg->{type
} eq 'zfspool' || $format eq 'qcow2')) {
369 die "non-migratable snapshot exists\n";
373 die "referenced by linked clone(s)\n"
374 if PVE
::Storage
::volume_is_base_and_used
($self->{storecfg
}, $volid);
377 PVE
::QemuServer
::foreach_volid
($conf, sub {
378 my ($volid, $attr) = @_;
379 eval { $test_volid->($volid, $attr); };
381 &$log_error($err, $volid);
385 foreach my $vol (sort keys %$local_volumes) {
386 my $ref = $local_volumes->{$vol}->{ref};
387 if ($ref eq 'storage') {
388 $self->log('info', "found local disk '$vol' (via storage)\n");
389 } elsif ($ref eq 'config') {
390 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
391 if $self->{running
} && !$self->{opts
}->{"with-local-disks"};
392 $self->log('info', "found local disk '$vol' (in current VM config)\n");
393 } elsif ($ref eq 'snapshot') {
394 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
396 $self->log('info', "found local disk '$vol'\n");
400 foreach my $vol (sort keys %$local_volumes_errors) {
401 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
403 foreach my $err (@$other_errors) {
404 $self->log('warn', "$err");
408 die "can't migrate VM - check log\n";
411 # additional checks for local storage
412 foreach my $volid (keys %$local_volumes) {
413 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
414 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $sid);
416 my $migratable = ($scfg->{type
} eq 'dir') || ($scfg->{type
} eq 'zfspool') ||
417 ($scfg->{type
} eq 'lvmthin') || ($scfg->{type
} eq 'lvm');
419 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
422 # image is a linked clone on local storage, se we can't migrate.
423 if (my $basename = (PVE
::Storage
::parse_volname
($self->{storecfg
}, $volid))[3]) {
424 die "can't migrate '$volid' as it's a clone of '$basename'";
430 $self->log('info', "copying disk images");
432 my $rep_cfg = PVE
::ReplicationConfig-
>new();
434 if (my $jobcfg = $rep_cfg->find_local_replication_job($vmid, $self->{node
})) {
435 die "can't live migrate VM with replicated volumes\n" if $self->{running
};
436 my $start_time = time();
437 my $logfunc = sub { my ($msg) = @_; $self->log('info', $msg); };
438 $rep_volumes = PVE
::Replication
::run_replication
(
439 'PVE::QemuConfig', $jobcfg, $start_time, $start_time, $logfunc);
440 $self->{replicated_volumes
} = $rep_volumes;
443 foreach my $volid (keys %$local_volumes) {
444 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
445 my $targetsid = $self->{opts
}->{targetstorage
} ?
$self->{opts
}->{targetstorage
} : $sid;
446 if ($self->{running
} && $local_volumes->{$volid}->{ref} eq 'config') {
447 push @{$self->{online_local_volumes
}}, $volid;
449 next if $rep_volumes->{$volid};
450 push @{$self->{volumes
}}, $volid;
451 my $insecure = $self->{opts
}->{migration_type
} eq 'insecure';
452 my $with_snapshots = $local_volumes->{$volid}->{snapshots
};
453 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{ssh_info
}, $targetsid,
454 undef, undef, undef, undef, $insecure, $with_snapshots);
458 die "Failed to sync data - $@" if $@;
461 sub cleanup_remotedisks
{
464 foreach my $target_drive (keys %{$self->{target_drive
}}) {
466 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{volid
});
467 my ($storeid, $volname) = PVE
::Storage
::parse_volume_id
($drive->{file
});
469 my $cmd = [@{$self->{rem_ssh
}}, 'pvesm', 'free', "$storeid:$volname"];
471 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
473 $self->log('err', $err);
480 my ($self, $vmid) = @_;
482 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
484 my $conf = $self->{vmconf
};
486 # set migrate lock in config file
487 $conf->{lock} = 'migrate';
488 PVE
::QemuConfig-
>write_config($vmid, $conf);
490 sync_disks
($self, $vmid);
495 my ($self, $vmid, $err) = @_;
497 $self->log('info', "aborting phase 1 - cleanup resources");
499 my $conf = $self->{vmconf
};
500 delete $conf->{lock};
501 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
503 $self->log('err', $err);
506 if ($self->{volumes
}) {
507 foreach my $volid (@{$self->{volumes
}}) {
508 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
509 # fixme: try to remove ?
515 my ($self, $vmid) = @_;
517 my $conf = $self->{vmconf
};
519 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
523 my $ruri; # the whole migration dst. URI (protocol:address[:port])
524 my $nodename = PVE
::INotify
::nodename
();
526 ## start on remote node
527 my $cmd = [@{$self->{rem_ssh
}}];
530 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
531 my $res = PVE
::QemuServer
::vm_mon_cmd
($vmid, 'query-spice');
532 $spice_ticket = $res->{ticket
};
535 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
537 my $migration_type = $self->{opts
}->{migration_type
};
539 push @$cmd, '--migration_type', $migration_type;
541 push @$cmd, '--migration_network', $self->{opts
}->{migration_network
}
542 if $self->{opts
}->{migration_network
};
544 if ($migration_type eq 'insecure') {
545 push @$cmd, '--stateuri', 'tcp';
547 push @$cmd, '--stateuri', 'unix';
550 if ($self->{forcemachine
}) {
551 push @$cmd, '--machine', $self->{forcemachine
};
554 if ($self->{online_local_volumes
}) {
555 push @$cmd, '--targetstorage', ($self->{opts
}->{targetstorage
} // '1');
560 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
561 # instead we pipe it through STDIN
562 PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
565 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
568 $ruri = "tcp:$raddr:$rport";
570 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
572 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
573 $ruri = "unix:$raddr";
575 elsif ($line =~ m/^migration listens on port (\d+)$/) {
576 $raddr = "localhost";
578 $ruri = "tcp:$raddr:$rport";
580 elsif ($line =~ m/^spice listens on port (\d+)$/) {
581 $spice_port = int($1);
583 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
585 my $nbd_uri = "nbd:$1:$2:exportname=$3";
586 my $targetdrive = $3;
587 $targetdrive =~ s/drive-//g;
589 $self->{target_drive
}->{$targetdrive}->{volid
} = $volid;
590 $self->{target_drive
}->{$targetdrive}->{nbd_uri
} = $nbd_uri;
595 $self->log('info', $line);
598 die "unable to detect remote migration address\n" if !$raddr;
600 $self->log('info', "start remote tunnel");
602 if ($migration_type eq 'secure') {
604 if ($ruri =~ /^unix:/) {
606 $self->{tunnel
} = $self->fork_tunnel("$raddr:$raddr");
607 $self->{tunnel
}->{sock_addr
} = $raddr;
609 my $unix_socket_try = 0; # wait for the socket to become ready
610 while (! -S
$raddr) {
612 if ($unix_socket_try > 100) {
614 $self->finish_tunnel($self->{tunnel
});
615 die "Timeout, migration socket $ruri did not get ready";
621 } elsif ($ruri =~ /^tcp:/) {
623 if ($raddr eq "localhost") {
624 # for backwards compatibility with older qemu-server versions
625 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
626 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
627 $tunnel_addr = "$lport:localhost:$rport";
630 $self->{tunnel
} = $self->fork_tunnel($tunnel_addr);
633 die "unsupported protocol in migration URI: $ruri\n";
636 #fork tunnel for insecure migration, to send faster commands like resume
637 $self->{tunnel
} = $self->fork_tunnel();
642 if ($self->{opts
}->{targetstorage
} && defined($self->{online_local_volumes
})) {
643 $self->{storage_migration
} = 1;
644 $self->{storage_migration_jobs
} = {};
645 $self->log('info', "starting storage migration");
647 die "The number of local disks does not match between the source and the destination.\n"
648 if (scalar(keys %{$self->{target_drive
}}) != scalar @{$self->{online_local_volumes
}});
649 foreach my $drive (keys %{$self->{target_drive
}}){
650 my $nbd_uri = $self->{target_drive
}->{$drive}->{nbd_uri
};
651 $self->log('info', "$drive: start migration to $nbd_uri");
652 PVE
::QemuServer
::qemu_drive_mirror
($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs
}, 1);
656 $self->log('info', "starting online/live migration on $ruri");
657 $self->{livemigration
} = 1;
660 my $defaults = PVE
::QemuServer
::load_defaults
();
662 # always set migrate speed (overwrite kvm default of 32m)
663 # we set a very hight default of 8192m which is basically unlimited
664 my $migrate_speed = $defaults->{migrate_speed
} || 8192;
665 $migrate_speed = $conf->{migrate_speed
} || $migrate_speed;
666 $migrate_speed = $migrate_speed * 1048576;
667 $self->log('info', "migrate_set_speed: $migrate_speed");
669 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_speed", value
=> int($migrate_speed));
671 $self->log('info', "migrate_set_speed error: $@") if $@;
673 my $migrate_downtime = $defaults->{migrate_downtime
};
674 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
675 if (defined($migrate_downtime)) {
676 $self->log('info', "migrate_set_downtime: $migrate_downtime");
678 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
680 $self->log('info', "migrate_set_downtime error: $@") if $@;
683 $self->log('info', "set migration_caps");
685 PVE
::QemuServer
::set_migration_caps
($vmid);
689 # set cachesize to 10% of the total memory
690 my $memory = $conf->{memory
} || $defaults->{memory
};
691 my $cachesize = int($memory * 1048576 / 10);
692 $cachesize = round_powerof2
($cachesize);
694 $self->log('info', "set cachesize: $cachesize");
696 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate-set-cache-size", value
=> int($cachesize));
698 $self->log('info', "migrate-set-cache-size error: $@") if $@;
700 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
701 my $rpcenv = PVE
::RPCEnvironment
::get
();
702 my $authuser = $rpcenv->get_user();
704 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
706 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
707 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
709 $self->log('info', "spice client_migrate_info");
712 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "client_migrate_info", protocol
=> 'spice',
713 hostname
=> $proxyticket, 'tls-port' => $spice_port,
714 'cert-subject' => $subject);
716 $self->log('info', "client_migrate_info error: $@") if $@;
720 $self->log('info', "start migrate command to $ruri");
722 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate", uri
=> $ruri);
725 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
728 my $usleep = 1000000;
732 my $downtimecounter = 0;
735 my $avglstat = $lstat/$i if $lstat;
740 $stat = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "query-migrate");
744 warn "query migrate failed: $err\n";
745 $self->log('info', "query migrate failed: $err");
746 if ($err_count <= 5) {
750 die "too many query migrate failures - aborting\n";
753 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(setup)$/im) {
758 if (defined($stat->{status
}) && $stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
761 if ($stat->{status
} eq 'completed') {
762 my $delay = time() - $start;
764 my $mbps = sprintf "%.2f", $memory / $delay;
765 my $downtime = $stat->{downtime
} || 0;
766 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
770 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
771 $self->log('info', "migration status error: $stat->{status}");
775 if ($stat->{status
} ne 'active') {
776 $self->log('info', "migration status: $stat->{status}");
780 if ($stat->{ram
}->{transferred
} ne $lstat) {
781 my $trans = $stat->{ram
}->{transferred
} || 0;
782 my $rem = $stat->{ram
}->{remaining
} || 0;
783 my $total = $stat->{ram
}->{total
} || 0;
784 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
785 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
786 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
787 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
788 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
789 # reduce sleep if remainig memory is lower than the average transfer speed
790 $usleep = 100000 if $avglstat && $rem < $avglstat;
792 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
793 "remaining ${rem}), total ${total})");
795 if (${xbzrlecachesize
}) {
796 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
799 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
804 if ($downtimecounter > 5) {
805 $downtimecounter = 0;
806 $migrate_downtime *= 2;
807 $self->log('info', "migrate_set_downtime: $migrate_downtime");
809 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
811 $self->log('info', "migrate_set_downtime error: $@") if $@;
817 $lstat = $stat->{ram
}->{transferred
};
821 die "unable to parse migration status '$stat->{status}' - aborting\n";
827 my ($self, $vmid, $err) = @_;
829 return if !$self->{errors
};
830 $self->{phase2errors
} = 1;
832 $self->log('info', "aborting phase 2 - cleanup resources");
834 $self->log('info', "migrate_cancel");
836 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_cancel");
838 $self->log('info', "migrate_cancel error: $@") if $@;
840 my $conf = $self->{vmconf
};
841 delete $conf->{lock};
842 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
844 $self->log('err', $err);
847 # cleanup ressources on target host
848 if ($self->{storage_migration
}) {
850 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
852 $self->log('err', $err);
855 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
857 $self->log('err', $err);
861 my $nodename = PVE
::INotify
::nodename
();
863 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
864 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
866 $self->log('err', $err);
870 if ($self->{tunnel
}) {
871 eval { finish_tunnel
($self, $self->{tunnel
}); };
873 $self->log('err', $err);
880 my ($self, $vmid) = @_;
882 my $volids = $self->{volumes
};
883 return if $self->{phase2errors
};
885 # destroy local copies
886 foreach my $volid (@$volids) {
887 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
889 $self->log('err', "removing local copy of '$volid' failed - $err");
891 last if $err =~ /^interrupted by signal$/;
897 my ($self, $vmid, $err) = @_;
899 my $conf = $self->{vmconf
};
900 return if $self->{phase2errors
};
902 my $tunnel = $self->{tunnel
};
904 if ($self->{storage_migration
}) {
906 eval { PVE
::QemuServer
::qemu_drive_mirror_monitor
($vmid, undef, $self->{storage_migration_jobs
}); };
909 eval { PVE
::QemuServer
::qemu_blockjobs_cancel
($vmid, $self->{storage_migration_jobs
}) };
910 eval { PVE
::QemuMigrate
::cleanup_remotedisks
($self) };
911 die "Failed to completed storage migration\n";
913 foreach my $target_drive (keys %{$self->{target_drive
}}) {
914 my $drive = PVE
::QemuServer
::parse_drive
($target_drive, $self->{target_drive
}->{$target_drive}->{volid
});
915 $conf->{$target_drive} = PVE
::QemuServer
::print_drive
($vmid, $drive);
916 PVE
::QemuConfig-
>write_config($vmid, $conf);
921 # transfer replication state before move config
922 $self->transfer_replication_state() if $self->{replicated_volumes
};
924 # move config to remote node
925 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
926 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
928 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
929 if !rename($conffile, $newconffile);
931 $self->switch_replication_job_target() if $self->{replicated_volumes
};
933 if ($self->{livemigration
}) {
934 if ($self->{storage_migration
}) {
935 # stop nbd server on remote vm - requirement for resume since 2.9
936 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'nbdstop', $vmid];
938 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
940 $self->log('err', $err);
945 # config moved and nbd server stopped - now we can resume vm on target
946 if ($tunnel && $tunnel->{version
} && $tunnel->{version
} >= 1) {
948 $self->write_tunnel($tunnel, 30, "resume $vmid");
951 $self->log('err', $err);
955 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
958 $self->log('err', $line);
960 eval { PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> $logf); };
962 $self->log('err', $err);
967 if ($self->{storage_migration
} && PVE
::QemuServer
::parse_guest_agent
($conf)->{fstrim_cloned_disks
} && $self->{running
}) {
968 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
969 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
973 # close tunnel on successful migration, on error phase2_cleanup closed it
975 eval { finish_tunnel
($self, $tunnel); };
977 $self->log('err', $err);
984 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
985 $self->log('info', "Waiting for spice server migration");
987 my $res = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'query-spice');
988 last if int($res->{'migrated'}) == 1;
996 # always stop local VM
997 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
999 $self->log('err', "stopping vm failed - $err");
1000 $self->{errors
} = 1;
1003 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1005 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
1006 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
1009 $self->log('err', $err);
1010 $self->{errors
} = 1;
1013 if($self->{storage_migration
}) {
1014 # destroy local copies
1015 my $volids = $self->{online_local_volumes
};
1017 foreach my $volid (@$volids) {
1018 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
1020 $self->log('err', "removing local copy of '$volid' failed - $err");
1021 $self->{errors
} = 1;
1022 last if $err =~ /^interrupted by signal$/;
1028 # clear migrate lock
1029 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
1030 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
1034 my ($self, $vmid) = @_;
1039 sub round_powerof2
{
1040 return 1 if $_[0] < 2;
1041 return 2 << int(log($_[0]-1)/log(2));