]>
git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
1 package PVE
::QemuMigrate
;
5 use PVE
::AbstractMigrate
;
8 use POSIX
qw( WNOHANG );
14 use Time
::HiRes
qw( usleep );
15 use PVE
::RPCEnvironment
;
17 use base
qw(PVE::AbstractMigrate);
19 sub fork_command_pipe
{
20 my ($self, $cmd) = @_;
22 my $reader = IO
::File-
>new();
23 my $writer = IO
::File-
>new();
29 eval { $cpid = open2
($reader, $writer, @$cmd); };
34 if ($orig_pid != $$) {
35 $self->log('err', "can't fork command pipe\n");
42 return { writer
=> $writer, reader
=> $reader, pid
=> $cpid };
45 sub finish_command_pipe
{
46 my ($self, $cmdpipe, $timeout) = @_;
48 my $cpid = $cmdpipe->{pid
};
49 return if !defined($cpid);
51 my $writer = $cmdpipe->{writer
};
52 my $reader = $cmdpipe->{reader
};
57 my $collect_child_process = sub {
58 my $res = waitpid($cpid, WNOHANG
);
59 if (defined($res) && ($res == $cpid)) {
60 delete $cmdpipe->{cpid
};
68 for (my $i = 0; $i < $timeout; $i++) {
69 return if &$collect_child_process();
74 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
78 for (my $i = 0; $i < 10; $i++) {
79 return if &$collect_child_process();
83 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
87 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
88 if !&$collect_child_process();
92 my ($self, $tunnel_addr) = @_;
94 my @localtunnelinfo = ('-L' , $tunnel_addr );
96 my $cmd = [@{$self->{rem_ssh
}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, 'qm', 'mtunnel' ];
98 my $tunnel = $self->fork_command_pipe($cmd);
100 my $reader = $tunnel->{reader
};
104 PVE
::Tools
::run_with_timeout
(60, sub { $helo = <$reader>; });
105 die "no reply\n" if !$helo;
106 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
107 die "got strange reply from mtunnel ('$helo')\n"
108 if $helo !~ m/^tunnel online$/;
113 $self->finish_command_pipe($tunnel);
114 die "can't open migration tunnel - $err";
120 my ($self, $tunnel) = @_;
122 my $writer = $tunnel->{writer
};
125 PVE
::Tools
::run_with_timeout
(30, sub {
126 print $writer "quit\n";
132 $self->finish_command_pipe($tunnel, 30);
134 if ($tunnel->{sock_addr
}) {
135 # ssh does not clean up on local host
136 my $cmd = ['rm', '-f', $tunnel->{sock_addr
}]; #
137 PVE
::Tools
::run_command
($cmd);
139 # .. and just to be sure check on remote side
140 unshift @{$cmd}, @{$self->{rem_ssh
}};
141 PVE
::Tools
::run_command
($cmd);
148 my ($self, $vmid, $code, @param) = @_;
150 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
154 my ($self, $vmid) = @_;
156 my $online = $self->{opts
}->{online
};
158 $self->{storecfg
} = PVE
::Storage
::config
();
161 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
163 PVE
::QemuConfig-
>check_lock($conf);
166 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
167 die "cant migrate running VM without --online\n" if !$online;
170 $self->{forcemachine
} = PVE
::QemuServer
::qemu_machine_pxe
($vmid, $conf);
174 if (my $loc_res = PVE
::QemuServer
::check_local_resources
($conf, 1)) {
175 if ($self->{running
} || !$self->{opts
}->{force
}) {
176 die "can't migrate VM which uses local devices\n";
178 $self->log('info', "migrating VM which uses local devices");
182 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
184 my $need_activate = [];
185 foreach my $volid (@$vollist) {
186 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
188 # check if storage is available on both nodes
189 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
190 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid, $self->{node
});
192 if ($scfg->{shared
}) {
193 # PVE::Storage::activate_storage checks this for non-shared storages
194 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
195 warn "Used shared storage '$sid' is not online on source node!\n"
196 if !$plugin->check_connection($sid, $scfg);
198 # only activate if not shared
199 push @$need_activate, $volid;
204 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
206 # test ssh connection
207 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
208 eval { $self->cmd_quiet($cmd); };
209 die "Can't connect to destination address using public key\n" if $@;
215 my ($self, $vmid) = @_;
217 $self->log('info', "copying disk images");
219 my $conf = $self->{vmconf
};
221 $self->{volumes
} = [];
232 my @sids = PVE
::Storage
::storage_ids
($self->{storecfg
});
233 foreach my $storeid (@sids) {
234 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $storeid);
235 next if $scfg->{shared
};
236 next if !PVE
::Storage
::storage_check_enabled
($self->{storecfg
}, $storeid, undef, 1);
238 # get list from PVE::Storage (for unused volumes)
239 my $dl = PVE
::Storage
::vdisk_list
($self->{storecfg
}, $storeid, $vmid);
240 PVE
::Storage
::foreach_volid
($dl, sub {
241 my ($volid, $sid, $volname) = @_;
243 # check if storage is available on target node
244 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid, $self->{node
});
246 $volhash->{$volid} = 1;
247 $sharedvm = 0; # there is a non-shared disk
251 # and add used, owned/non-shared disks (just to be sure we have all)
253 PVE
::QemuServer
::foreach_volid
($conf, sub {
254 my ($volid, $is_cdrom) = @_;
258 die "can't migrate local file/device '$volid'\n" if $volid =~ m
|^/|;
261 die "cant migrate local cdrom drive\n" if $volid eq 'cdrom';
262 return if $volid eq 'none';
263 $cdromhash->{$volid} = 1;
266 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
268 # check if storage is available on both nodes
269 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
270 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid, $self->{node
});
272 return if $scfg->{shared
};
274 die "can't migrate local cdrom '$volid'\n" if $cdromhash->{$volid};
278 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
280 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
281 if !$owner || ($owner != $self->{vmid
});
283 $volhash->{$volid} = 1;
286 if ($self->{running
} && !$sharedvm) {
287 die "can't do online migration - VM uses local disks\n";
290 # do some checks first
291 foreach my $volid (keys %$volhash) {
292 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
293 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $sid);
295 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
296 if (!($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'zfspool') && (!$sharedvm));
298 # if file, check if a backing file exist
299 if (!($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'zfspool') && (!$sharedvm)) {
300 my (undef, undef, undef, $parent) = PVE
::Storage
::volume_size_info
($self->{storecfg
}, $volid, 1);
301 die "can't migrate '$volid' as it's a clone of '$parent'" if $parent;
305 foreach my $volid (keys %$volhash) {
306 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
307 push @{$self->{volumes
}}, $volid;
308 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{nodeip
}, $sid);
311 die "Failed to sync data - $@" if $@;
315 my ($self, $vmid) = @_;
317 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
319 my $conf = $self->{vmconf
};
321 # set migrate lock in config file
322 $conf->{lock} = 'migrate';
323 PVE
::QemuConfig-
>write_config($vmid, $conf);
325 sync_disks
($self, $vmid);
330 my ($self, $vmid, $err) = @_;
332 $self->log('info', "aborting phase 1 - cleanup resources");
334 my $conf = $self->{vmconf
};
335 delete $conf->{lock};
336 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
338 $self->log('err', $err);
341 if ($self->{volumes
}) {
342 foreach my $volid (@{$self->{volumes
}}) {
343 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
344 # fixme: try to remove ?
350 my ($self, $vmid) = @_;
352 my $conf = $self->{vmconf
};
354 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
358 my $ruri; # the whole migration dst. URI (protocol:address[:port])
359 my $nodename = PVE
::INotify
::nodename
();
361 ## start on remote node
362 my $cmd = [@{$self->{rem_ssh
}}];
365 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
366 my $res = PVE
::QemuServer
::vm_mon_cmd
($vmid, 'query-spice');
367 $spice_ticket = $res->{ticket
};
370 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
372 # we use TCP only for unsecure migrations as TCP ssh forward tunnels often
373 # did appeared to late (they are hard, if not impossible, to check for)
374 # secure migration use UNIX sockets now, this *breaks* compatibilty when trying
375 # to migrate from new to old but *not* from old to new.
376 my $datacenterconf = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
377 my $secure_migration = ($datacenterconf->{migration_unsecure
}) ?
0 : 1;
379 if (!$secure_migration) {
380 push @$cmd, '--stateuri', 'tcp';
382 push @$cmd, '--stateuri', 'unix';
385 if ($self->{forcemachine
}) {
386 push @$cmd, '--machine', $self->{forcemachine
};
391 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
392 # instead we pipe it through STDIN
393 PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
396 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
399 $ruri = "tcp:$raddr:$rport";
401 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
403 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
404 $ruri = "unix:$raddr";
406 elsif ($line =~ m/^migration listens on port (\d+)$/) {
407 $raddr = "localhost";
409 $ruri = "tcp:$raddr:$rport";
411 elsif ($line =~ m/^spice listens on port (\d+)$/) {
412 $spice_port = int($1);
416 $self->log('info', $line);
419 die "unable to detect remote migration address\n" if !$raddr;
421 if ($secure_migration) {
422 $self->log('info', "start remote tunnel");
424 if ($ruri =~ /^unix:/) {
425 $self->{tunnel
} = $self->fork_tunnel("$raddr:$raddr");
426 $self->{tunnel
}->{sock_addr
} = $raddr;
428 my $unix_socket_try = 0; # wait for the socket to become ready
429 while (! -S
$raddr) {
431 if ($unix_socket_try > 100) {
433 $self->finish_tunnel($self->{tunnel
});
434 die "Timeout, migration socket $ruri did not get ready";
440 } elsif ($ruri =~ /^tcp:/) {
441 # for backwards compatibility with older qemu-server versions
442 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
443 my $lport = PVE
::Tools
::next_migrate_port
($pfamily);
445 $self->{tunnel
} = $self->fork_tunnel("$lport:localhost:$rport");
448 die "unsupported protocol in migration URI: $ruri\n";
453 $self->log('info', "starting online/live migration on $ruri");
454 $self->{livemigration
} = 1;
457 my $defaults = PVE
::QemuServer
::load_defaults
();
459 # always set migrate speed (overwrite kvm default of 32m)
460 # we set a very hight default of 8192m which is basically unlimited
461 my $migrate_speed = $defaults->{migrate_speed
} || 8192;
462 $migrate_speed = $conf->{migrate_speed
} || $migrate_speed;
463 $migrate_speed = $migrate_speed * 1048576;
464 $self->log('info', "migrate_set_speed: $migrate_speed");
466 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_speed", value
=> int($migrate_speed));
468 $self->log('info', "migrate_set_speed error: $@") if $@;
470 my $migrate_downtime = $defaults->{migrate_downtime
};
471 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
472 if (defined($migrate_downtime)) {
473 $self->log('info', "migrate_set_downtime: $migrate_downtime");
475 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
477 $self->log('info', "migrate_set_downtime error: $@") if $@;
481 PVE
::QemuServer
::set_migration_caps
($vmid);
485 #set cachesize 10% of the total memory
486 my $cachesize = int($conf->{memory
}*1048576/10);
488 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate-set-cache-size", value
=> $cachesize);
491 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
492 my $rpcenv = PVE
::RPCEnvironment
::get
();
493 my $authuser = $rpcenv->get_user();
495 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
497 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
498 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
500 $self->log('info', "spice client_migrate_info");
503 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "client_migrate_info", protocol
=> 'spice',
504 hostname
=> $proxyticket, 'tls-port' => $spice_port,
505 'cert-subject' => $subject);
507 $self->log('info', "client_migrate_info error: $@") if $@;
512 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate", uri
=> $ruri);
515 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
518 my $usleep = 2000000;
522 my $downtimecounter = 0;
525 my $avglstat = $lstat/$i if $lstat;
530 $stat = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "query-migrate");
534 warn "query migrate failed: $err\n";
535 if ($err_count <= 5) {
539 die "too many query migrate failures - aborting\n";
542 if ($stat->{status
} =~ m/^(setup)$/im) {
547 if ($stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
550 if ($stat->{status
} eq 'completed') {
551 my $delay = time() - $start;
553 my $mbps = sprintf "%.2f", $conf->{memory
}/$delay;
554 my $downtime = $stat->{downtime
} || 0;
555 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
559 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
563 if ($stat->{status
} ne 'active') {
564 $self->log('info', "migration status: $stat->{status}");
568 if ($stat->{ram
}->{transferred
} ne $lstat) {
569 my $trans = $stat->{ram
}->{transferred
} || 0;
570 my $rem = $stat->{ram
}->{remaining
} || 0;
571 my $total = $stat->{ram
}->{total
} || 0;
572 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
573 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
574 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
575 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
576 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
577 #reduce sleep if remainig memory if lower than the everage transfert
578 $usleep = 300000 if $avglstat && $rem < $avglstat;
580 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
581 "remaining ${rem}), total ${total})");
583 if (${xbzrlecachesize
}) {
584 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
587 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
592 if ($downtimecounter > 5) {
593 $downtimecounter = 0;
594 $migrate_downtime *= 2;
595 $self->log('info', "migrate_set_downtime: $migrate_downtime");
597 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
599 $self->log('info', "migrate_set_downtime error: $@") if $@;
605 $lstat = $stat->{ram
}->{transferred
};
609 die "unable to parse migration status '$stat->{status}' - aborting\n";
612 #to be sure tat the tunnel is closed
613 if ($self->{tunnel
}) {
614 eval { finish_tunnel
($self, $self->{tunnel
}); };
616 $self->log('err', $err);
623 my ($self, $vmid, $err) = @_;
625 return if !$self->{errors
};
626 $self->{phase2errors
} = 1;
628 $self->log('info', "aborting phase 2 - cleanup resources");
630 $self->log('info', "migrate_cancel");
632 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_cancel");
634 $self->log('info', "migrate_cancel error: $@") if $@;
636 my $conf = $self->{vmconf
};
637 delete $conf->{lock};
638 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
640 $self->log('err', $err);
643 # cleanup ressources on target host
644 my $nodename = PVE
::INotify
::nodename
();
646 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
647 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
649 $self->log('err', $err);
653 if ($self->{tunnel
}) {
654 eval { finish_tunnel
($self, $self->{tunnel
}); };
656 $self->log('err', $err);
663 my ($self, $vmid) = @_;
665 my $volids = $self->{volumes
};
666 return if $self->{phase2errors
};
668 # destroy local copies
669 foreach my $volid (@$volids) {
670 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
672 $self->log('err', "removing local copy of '$volid' failed - $err");
674 last if $err =~ /^interrupted by signal$/;
680 my ($self, $vmid, $err) = @_;
682 my $conf = $self->{vmconf
};
683 return if $self->{phase2errors
};
685 # move config to remote node
686 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
687 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
689 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
690 if !rename($conffile, $newconffile);
692 if ($self->{livemigration
}) {
693 # now that config file is move, we can resume vm on target if livemigrate
694 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
695 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {},
698 $self->log('err', $line);
702 $self->log('err', $err);
710 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
711 $self->log('info', "Waiting for spice server migration");
713 my $res = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'query-spice');
714 last if int($res->{'migrated'}) == 1;
722 # always stop local VM
723 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
725 $self->log('err', "stopping vm failed - $err");
729 # always deactivate volumes - avoid lvm LVs to be active on several nodes
731 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
732 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
735 $self->log('err', $err);
740 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
741 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
745 my ($self, $vmid) = @_;