]>
git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
954de3c09c3513ce76a4821ece0c8798b9bd2f36
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, $nodeip, $lport, $rport) = @_;
94 my @localtunnelinfo = $lport ?
('-L' , "$lport:localhost:$rport" ) : ();
96 my $cmd = [@{$self->{rem_ssh
}}, @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);
138 my ($self, $vmid, $code, @param) = @_;
140 return PVE
::QemuConfig-
>lock_config($vmid, $code, @param);
144 my ($self, $vmid) = @_;
146 my $online = $self->{opts
}->{online
};
148 $self->{storecfg
} = PVE
::Storage
::config
();
151 my $conf = $self->{vmconf
} = PVE
::QemuConfig-
>load_config($vmid);
153 PVE
::QemuConfig-
>check_lock($conf);
156 if (my $pid = PVE
::QemuServer
::check_running
($vmid)) {
157 die "cant migrate running VM without --online\n" if !$online;
160 $self->{forcemachine
} = PVE
::QemuServer
::qemu_machine_pxe
($vmid, $conf);
164 if (my $loc_res = PVE
::QemuServer
::check_local_resources
($conf, 1)) {
165 if ($self->{running
} || !$self->{opts
}->{force
}) {
166 die "can't migrate VM which uses local devices\n";
168 $self->log('info', "migrating VM which uses local devices");
172 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
174 my $need_activate = [];
175 foreach my $volid (@$vollist) {
176 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid, 1);
178 # check if storage is available on both nodes
179 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
180 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid, $self->{node
});
182 if ($scfg->{shared
}) {
183 # PVE::Storage::activate_storage checks this for non-shared storages
184 my $plugin = PVE
::Storage
::Plugin-
>lookup($scfg->{type
});
185 warn "Used shared storage '$sid' is not online on source node!\n"
186 if !$plugin->check_connection($sid, $scfg);
188 # only activate if not shared
189 push @$need_activate, $volid;
194 PVE
::Storage
::activate_volumes
($self->{storecfg
}, $need_activate);
196 # test ssh connection
197 my $cmd = [ @{$self->{rem_ssh
}}, '/bin/true' ];
198 eval { $self->cmd_quiet($cmd); };
199 die "Can't connect to destination address using public key\n" if $@;
205 my ($self, $vmid) = @_;
207 $self->log('info', "copying disk images");
209 my $conf = $self->{vmconf
};
211 $self->{volumes
} = [];
222 my @sids = PVE
::Storage
::storage_ids
($self->{storecfg
});
223 foreach my $storeid (@sids) {
224 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $storeid);
225 next if $scfg->{shared
};
226 next if !PVE
::Storage
::storage_check_enabled
($self->{storecfg
}, $storeid, undef, 1);
228 # get list from PVE::Storage (for unused volumes)
229 my $dl = PVE
::Storage
::vdisk_list
($self->{storecfg
}, $storeid, $vmid);
230 PVE
::Storage
::foreach_volid
($dl, sub {
231 my ($volid, $sid, $volname) = @_;
233 # check if storage is available on target node
234 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid, $self->{node
});
236 $volhash->{$volid} = 1;
237 $sharedvm = 0; # there is a non-shared disk
241 # and add used, owned/non-shared disks (just to be sure we have all)
243 PVE
::QemuServer
::foreach_volid
($conf, sub {
244 my ($volid, $is_cdrom) = @_;
248 die "can't migrate local file/device '$volid'\n" if $volid =~ m
|^/|;
251 die "cant migrate local cdrom drive\n" if $volid eq 'cdrom';
252 return if $volid eq 'none';
253 $cdromhash->{$volid} = 1;
256 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
258 # check if storage is available on both nodes
259 my $scfg = PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid);
260 PVE
::Storage
::storage_check_node
($self->{storecfg
}, $sid, $self->{node
});
262 return if $scfg->{shared
};
264 die "can't migrate local cdrom '$volid'\n" if $cdromhash->{$volid};
268 my ($path, $owner) = PVE
::Storage
::path
($self->{storecfg
}, $volid);
270 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
271 if !$owner || ($owner != $self->{vmid
});
273 $volhash->{$volid} = 1;
276 if ($self->{running
} && !$sharedvm) {
277 die "can't do online migration - VM uses local disks\n";
280 # do some checks first
281 foreach my $volid (keys %$volhash) {
282 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
283 my $scfg = PVE
::Storage
::storage_config
($self->{storecfg
}, $sid);
285 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
286 if (!($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'zfspool') && (!$sharedvm));
288 # if file, check if a backing file exist
289 if (!($scfg->{type
} eq 'dir' || $scfg->{type
} eq 'zfspool') && (!$sharedvm)) {
290 my (undef, undef, undef, $parent) = PVE
::Storage
::volume_size_info
($self->{storecfg
}, $volid, 1);
291 die "can't migrate '$volid' as it's a clone of '$parent'" if $parent;
295 foreach my $volid (keys %$volhash) {
296 my ($sid, $volname) = PVE
::Storage
::parse_volume_id
($volid);
297 push @{$self->{volumes
}}, $volid;
298 PVE
::Storage
::storage_migrate
($self->{storecfg
}, $volid, $self->{nodeip
}, $sid);
301 die "Failed to sync data - $@" if $@;
305 my ($self, $vmid) = @_;
307 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
309 my $conf = $self->{vmconf
};
311 # set migrate lock in config file
312 $conf->{lock} = 'migrate';
313 PVE
::QemuConfig-
>write_config($vmid, $conf);
315 sync_disks
($self, $vmid);
320 my ($self, $vmid, $err) = @_;
322 $self->log('info', "aborting phase 1 - cleanup resources");
324 my $conf = $self->{vmconf
};
325 delete $conf->{lock};
326 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
328 $self->log('err', $err);
331 if ($self->{volumes
}) {
332 foreach my $volid (@{$self->{volumes
}}) {
333 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
334 # fixme: try to remove ?
340 my ($self, $vmid) = @_;
342 my $conf = $self->{vmconf
};
344 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
348 my $nodename = PVE
::INotify
::nodename
();
350 ## start on remote node
351 my $cmd = [@{$self->{rem_ssh
}}];
354 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
355 my $res = PVE
::QemuServer
::vm_mon_cmd
($vmid, 'query-spice');
356 $spice_ticket = $res->{ticket
};
359 push @$cmd , 'qm', 'start', $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename;
361 if ($self->{forcemachine
}) {
362 push @$cmd, '--machine', $self->{forcemachine
};
367 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
368 # instead we pipe it through STDIN
369 PVE
::Tools
::run_command
($cmd, input
=> $spice_ticket, outfunc
=> sub {
372 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
376 elsif ($line =~ m/^migration listens on port (\d+)$/) {
377 $raddr = "localhost";
380 elsif ($line =~ m/^spice listens on port (\d+)$/) {
381 $spice_port = int($1);
385 $self->log('info', $line);
388 die "unable to detect remote migration address\n" if !$raddr;
390 ## create tunnel to remote port
391 $self->log('info', "starting ssh migration tunnel");
392 my $pfamily = PVE
::Tools
::get_host_address_family
($nodename);
393 my $lport = ($raddr eq "localhost") ? PVE
::Tools
::next_migrate_port
($pfamily) : undef;
394 $self->{tunnel
} = $self->fork_tunnel($self->{nodeip
}, $lport, $rport);
397 $self->log('info', "starting online/live migration on $raddr:$rport");
398 $self->{livemigration
} = 1;
401 my $defaults = PVE
::QemuServer
::load_defaults
();
403 # always set migrate speed (overwrite kvm default of 32m)
404 # we set a very hight default of 8192m which is basically unlimited
405 my $migrate_speed = $defaults->{migrate_speed
} || 8192;
406 $migrate_speed = $conf->{migrate_speed
} || $migrate_speed;
407 $migrate_speed = $migrate_speed * 1048576;
408 $self->log('info', "migrate_set_speed: $migrate_speed");
410 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_speed", value
=> int($migrate_speed));
412 $self->log('info', "migrate_set_speed error: $@") if $@;
414 my $migrate_downtime = $defaults->{migrate_downtime
};
415 $migrate_downtime = $conf->{migrate_downtime
} if defined($conf->{migrate_downtime
});
416 if (defined($migrate_downtime)) {
417 $self->log('info', "migrate_set_downtime: $migrate_downtime");
419 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
421 $self->log('info', "migrate_set_downtime error: $@") if $@;
425 PVE
::QemuServer
::set_migration_caps
($vmid);
429 #set cachesize 10% of the total memory
430 my $cachesize = int($conf->{memory
}*1048576/10);
432 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate-set-cache-size", value
=> $cachesize);
435 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
})) {
436 my $rpcenv = PVE
::RPCEnvironment
::get
();
437 my $authuser = $rpcenv->get_user();
439 my (undef, $proxyticket) = PVE
::AccessControl
::assemble_spice_ticket
($authuser, $vmid, $self->{node
});
441 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
442 my $subject = PVE
::AccessControl
::read_x509_subject_spice
($filename);
444 $self->log('info', "spice client_migrate_info");
447 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "client_migrate_info", protocol
=> 'spice',
448 hostname
=> $proxyticket, 'tls-port' => $spice_port,
449 'cert-subject' => $subject);
451 $self->log('info', "client_migrate_info error: $@") if $@;
456 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate", uri
=> "tcp:$raddr:$rport");
459 $self->log('info', "migrate uri => tcp:$raddr:$rport failed: $merr") if $merr;
462 my $usleep = 2000000;
466 my $downtimecounter = 0;
469 my $avglstat = $lstat/$i if $lstat;
474 $stat = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "query-migrate");
478 warn "query migrate failed: $err\n";
479 if ($err_count <= 5) {
483 die "too many query migrate failures - aborting\n";
486 if ($stat->{status
} =~ m/^(setup)$/im) {
491 if ($stat->{status
} =~ m/^(active|completed|failed|cancelled)$/im) {
494 if ($stat->{status
} eq 'completed') {
495 my $delay = time() - $start;
497 my $mbps = sprintf "%.2f", $conf->{memory
}/$delay;
498 my $downtime = $stat->{downtime
} || 0;
499 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
503 if ($stat->{status
} eq 'failed' || $stat->{status
} eq 'cancelled') {
507 if ($stat->{status
} ne 'active') {
508 $self->log('info', "migration status: $stat->{status}");
512 if ($stat->{ram
}->{transferred
} ne $lstat) {
513 my $trans = $stat->{ram
}->{transferred
} || 0;
514 my $rem = $stat->{ram
}->{remaining
} || 0;
515 my $total = $stat->{ram
}->{total
} || 0;
516 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
517 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
518 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
519 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
520 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
521 #reduce sleep if remainig memory if lower than the everage transfert
522 $usleep = 300000 if $avglstat && $rem < $avglstat;
524 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
525 "remaining ${rem}), total ${total})");
527 if (${xbzrlecachesize
}) {
528 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
531 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
536 if ($downtimecounter > 5) {
537 $downtimecounter = 0;
538 $migrate_downtime *= 2;
539 $self->log('info', "migrate_set_downtime: $migrate_downtime");
541 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_set_downtime", value
=> int($migrate_downtime*100)/100);
543 $self->log('info', "migrate_set_downtime error: $@") if $@;
549 $lstat = $stat->{ram
}->{transferred
};
553 die "unable to parse migration status '$stat->{status}' - aborting\n";
556 #to be sure tat the tunnel is closed
557 if ($self->{tunnel
}) {
558 eval { finish_tunnel
($self, $self->{tunnel
}); };
560 $self->log('err', $err);
567 my ($self, $vmid, $err) = @_;
569 return if !$self->{errors
};
570 $self->{phase2errors
} = 1;
572 $self->log('info', "aborting phase 2 - cleanup resources");
574 $self->log('info', "migrate_cancel");
576 PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, "migrate_cancel");
578 $self->log('info', "migrate_cancel error: $@") if $@;
580 my $conf = $self->{vmconf
};
581 delete $conf->{lock};
582 eval { PVE
::QemuConfig-
>write_config($vmid, $conf) };
584 $self->log('err', $err);
587 # cleanup ressources on target host
588 my $nodename = PVE
::INotify
::nodename
();
590 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
591 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {}, errfunc
=> sub {}) };
593 $self->log('err', $err);
597 if ($self->{tunnel
}) {
598 eval { finish_tunnel
($self, $self->{tunnel
}); };
600 $self->log('err', $err);
607 my ($self, $vmid) = @_;
609 my $volids = $self->{volumes
};
610 return if $self->{phase2errors
};
612 # destroy local copies
613 foreach my $volid (@$volids) {
614 eval { PVE
::Storage
::vdisk_free
($self->{storecfg
}, $volid); };
616 $self->log('err', "removing local copy of '$volid' failed - $err");
618 last if $err =~ /^interrupted by signal$/;
624 my ($self, $vmid, $err) = @_;
626 my $conf = $self->{vmconf
};
627 return if $self->{phase2errors
};
629 # move config to remote node
630 my $conffile = PVE
::QemuConfig-
>config_file($vmid);
631 my $newconffile = PVE
::QemuConfig-
>config_file($vmid, $self->{node
});
633 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
634 if !rename($conffile, $newconffile);
636 if ($self->{livemigration
}) {
637 # now that config file is move, we can resume vm on target if livemigrate
638 my $cmd = [@{$self->{rem_ssh
}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
639 eval{ PVE
::Tools
::run_command
($cmd, outfunc
=> sub {},
642 $self->log('err', $line);
646 $self->log('err', $err);
654 if (PVE
::QemuServer
::vga_conf_has_spice
($conf->{vga
}) && $self->{running
}) {
655 $self->log('info', "Waiting for spice server migration");
657 my $res = PVE
::QemuServer
::vm_mon_cmd_nocheck
($vmid, 'query-spice');
658 last if int($res->{'migrated'}) == 1;
666 # always stop local VM
667 eval { PVE
::QemuServer
::vm_stop
($self->{storecfg
}, $vmid, 1, 1); };
669 $self->log('err', "stopping vm failed - $err");
673 # always deactivate volumes - avoid lvm LVs to be active on several nodes
675 my $vollist = PVE
::QemuServer
::get_vm_volumes
($conf);
676 PVE
::Storage
::deactivate_volumes
($self->{storecfg
}, $vollist);
679 $self->log('err', $err);
684 my $cmd = [ @{$self->{rem_ssh
}}, 'qm', 'unlock', $vmid ];
685 $self->cmd_logerr($cmd, errmsg
=> "failed to clear migrate lock");
689 my ($self, $vmid) = @_;