]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
use qom-get to check if pxe file are used V2
[qemu-server.git] / PVE / QemuMigrate.pm
1 package PVE::QemuMigrate;
2
3 use strict;
4 use warnings;
5 use PVE::AbstractMigrate;
6 use IO::File;
7 use IPC::Open2;
8 use PVE::INotify;
9 use PVE::Tools;
10 use PVE::Cluster;
11 use PVE::Storage;
12 use PVE::QemuServer;
13 use Time::HiRes qw( usleep );
14 use PVE::RPCEnvironment;
15
16 use base qw(PVE::AbstractMigrate);
17
18 sub fork_command_pipe {
19 my ($self, $cmd) = @_;
20
21 my $reader = IO::File->new();
22 my $writer = IO::File->new();
23
24 my $orig_pid = $$;
25
26 my $cpid;
27
28 eval { $cpid = open2($reader, $writer, @$cmd); };
29
30 my $err = $@;
31
32 # catch exec errors
33 if ($orig_pid != $$) {
34 $self->log('err', "can't fork command pipe\n");
35 POSIX::_exit(1);
36 kill('KILL', $$);
37 }
38
39 die $err if $err;
40
41 return { writer => $writer, reader => $reader, pid => $cpid };
42 }
43
44 sub finish_command_pipe {
45 my ($self, $cmdpipe, $timeout) = @_;
46
47 my $writer = $cmdpipe->{writer};
48 my $reader = $cmdpipe->{reader};
49
50 $writer->close();
51 $reader->close();
52
53 my $cpid = $cmdpipe->{pid};
54
55 if ($timeout) {
56 for (my $i = 0; $i < $timeout; $i++) {
57 return if !PVE::ProcFSTools::check_process_running($cpid);
58 sleep(1);
59 }
60 }
61
62 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
63 kill(15, $cpid);
64
65 # wait again
66 for (my $i = 0; $i < 10; $i++) {
67 return if !PVE::ProcFSTools::check_process_running($cpid);
68 sleep(1);
69 }
70
71 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
72 kill 9, $cpid;
73 sleep 1;
74 }
75
76 sub fork_tunnel {
77 my ($self, $nodeip, $lport, $rport) = @_;
78
79 my @localtunnelinfo = $lport ? ('-L' , "$lport:localhost:$rport" ) : ();
80
81 my $cmd = [@{$self->{rem_ssh}}, @localtunnelinfo, 'qm', 'mtunnel' ];
82
83 my $tunnel = $self->fork_command_pipe($cmd);
84
85 my $reader = $tunnel->{reader};
86
87 my $helo;
88 eval {
89 PVE::Tools::run_with_timeout(60, sub { $helo = <$reader>; });
90 die "no reply\n" if !$helo;
91 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
92 die "got strange reply from mtunnel ('$helo')\n"
93 if $helo !~ m/^tunnel online$/;
94 };
95 my $err = $@;
96
97 if ($err) {
98 $self->finish_command_pipe($tunnel);
99 die "can't open migration tunnel - $err";
100 }
101 return $tunnel;
102 }
103
104 sub finish_tunnel {
105 my ($self, $tunnel) = @_;
106
107 my $writer = $tunnel->{writer};
108
109 eval {
110 PVE::Tools::run_with_timeout(30, sub {
111 print $writer "quit\n";
112 $writer->flush();
113 });
114 };
115 my $err = $@;
116
117 $self->finish_command_pipe($tunnel, 30);
118
119 die $err if $err;
120 }
121
122 sub lock_vm {
123 my ($self, $vmid, $code, @param) = @_;
124
125 return PVE::QemuServer::lock_config($vmid, $code, @param);
126 }
127
128 sub prepare {
129 my ($self, $vmid) = @_;
130
131 my $online = $self->{opts}->{online};
132
133 $self->{storecfg} = PVE::Storage::config();
134
135 # test is VM exist
136 my $conf = $self->{vmconf} = PVE::QemuServer::load_config($vmid);
137
138 PVE::QemuServer::check_lock($conf);
139
140 my $running = 0;
141 if (my $pid = PVE::QemuServer::check_running($vmid)) {
142 die "cant migrate running VM without --online\n" if !$online;
143 $running = $pid;
144 $self->{forcemachine} = PVE::QemuServer::get_current_qemu_machine($vmid);
145
146 foreach my $opt (keys %$conf) {
147 next if $opt !~ m/^net(\d+)$/;
148 my $net = PVE::QemuServer::parse_net($conf->{$opt});
149 next if !$net;
150 my $romfile = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'qom-get', path => $opt, property => 'romfile');
151 $self->{forcemachine} .= '.pxe' if $romfile =~ m/pxe/;
152 last;
153 }
154
155 }
156
157 if (my $loc_res = PVE::QemuServer::check_local_resources($conf, 1)) {
158 if ($self->{running} || !$self->{opts}->{force}) {
159 die "can't migrate VM which uses local devices\n";
160 } else {
161 $self->log('info', "migrating VM which uses local devices");
162 }
163 }
164
165 # activate volumes
166 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
167 PVE::Storage::activate_volumes($self->{storecfg}, $vollist);
168
169 # fixme: check if storage is available on both nodes
170
171 # test ssh connection
172 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
173 eval { $self->cmd_quiet($cmd); };
174 die "Can't connect to destination address using public key\n" if $@;
175
176 return $running;
177 }
178
179 sub sync_disks {
180 my ($self, $vmid) = @_;
181
182 $self->log('info', "copying disk images");
183
184 my $conf = $self->{vmconf};
185
186 $self->{volumes} = [];
187
188 my $res = [];
189
190 eval {
191
192 my $volhash = {};
193 my $cdromhash = {};
194
195 my $sharedvm = 1;
196
197 my @sids = PVE::Storage::storage_ids($self->{storecfg});
198 foreach my $storeid (@sids) {
199 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
200 next if $scfg->{shared};
201 next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
202
203 # get list from PVE::Storage (for unused volumes)
204 my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
205 PVE::Storage::foreach_volid($dl, sub {
206 my ($volid, $sid, $volname) = @_;
207
208 # check if storage is available on target node
209 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
210
211 $volhash->{$volid} = 1;
212 $sharedvm = 0; # there is a non-shared disk
213 });
214 }
215
216 # and add used, owned/non-shared disks (just to be sure we have all)
217
218 PVE::QemuServer::foreach_volid($conf, sub {
219 my ($volid, $is_cdrom) = @_;
220
221 return if !$volid;
222
223 die "cant migrate local file/device '$volid'\n" if $volid =~ m|^/|;
224
225 if ($is_cdrom) {
226 die "cant migrate local cdrom drive\n" if $volid eq 'cdrom';
227 return if $volid eq 'none';
228 $cdromhash->{$volid} = 1;
229 }
230
231 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
232
233 # check if storage is available on both nodes
234 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
235 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
236
237 return if $scfg->{shared};
238
239 die "can't migrate local cdrom '$volid'\n" if $cdromhash->{$volid};
240
241 $sharedvm = 0;
242
243 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
244
245 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
246 if !$owner || ($owner != $self->{vmid});
247
248 $volhash->{$volid} = 1;
249 });
250
251 if ($self->{running} && !$sharedvm) {
252 die "can't do online migration - VM uses local disks\n";
253 }
254
255 # do some checks first
256 foreach my $volid (keys %$volhash) {
257 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
258 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $sid);
259
260 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
261 if (!($scfg->{type} eq 'dir' || $scfg->{type} eq 'zfspool') && (!$sharedvm));
262
263 # if file, check if a backing file exist
264 if (!($scfg->{type} eq 'dir' || $scfg->{type} eq 'zfspool') && (!$sharedvm)) {
265 my (undef, undef, undef, $parent) = PVE::Storage::volume_size_info($self->{storecfg}, $volid, 1);
266 die "can't migrate '$volid' as it's a clone of '$parent'" if $parent;
267 }
268 }
269
270 foreach my $volid (keys %$volhash) {
271 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
272 push @{$self->{volumes}}, $volid;
273 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{nodeip}, $sid);
274 }
275 };
276 die "Failed to sync data - $@" if $@;
277 }
278
279 sub phase1 {
280 my ($self, $vmid) = @_;
281
282 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
283
284 my $conf = $self->{vmconf};
285
286 # set migrate lock in config file
287 $conf->{lock} = 'migrate';
288 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
289
290 sync_disks($self, $vmid);
291
292 };
293
294 sub phase1_cleanup {
295 my ($self, $vmid, $err) = @_;
296
297 $self->log('info', "aborting phase 1 - cleanup resources");
298
299 my $conf = $self->{vmconf};
300 delete $conf->{lock};
301 eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
302 if (my $err = $@) {
303 $self->log('err', $err);
304 }
305
306 if ($self->{volumes}) {
307 foreach my $volid (@{$self->{volumes}}) {
308 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
309 # fixme: try to remove ?
310 }
311 }
312 }
313
314 sub phase2 {
315 my ($self, $vmid) = @_;
316
317 my $conf = $self->{vmconf};
318
319 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
320
321 my $raddr;
322 my $rport;
323 my $nodename = PVE::INotify::nodename();
324
325 ## start on remote node
326 my $cmd = [@{$self->{rem_ssh}}];
327
328 my $spice_ticket;
329 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
330 my $res = PVE::QemuServer::vm_mon_cmd($vmid, 'query-spice');
331 $spice_ticket = $res->{ticket};
332 }
333
334 push @$cmd , 'qm', 'start', $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename;
335
336 if ($self->{forcemachine}) {
337 push @$cmd, '--machine', $self->{forcemachine};
338 }
339
340 my $spice_port;
341
342 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
343 # instead we pipe it through STDIN
344 PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
345 my $line = shift;
346
347 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
348 $raddr = $1;
349 $rport = int($2);
350 }
351 elsif ($line =~ m/^migration listens on port (\d+)$/) {
352 $raddr = "localhost";
353 $rport = int($1);
354 }
355 elsif ($line =~ m/^spice listens on port (\d+)$/) {
356 $spice_port = int($1);
357 }
358 }, errfunc => sub {
359 my $line = shift;
360 $self->log('info', $line);
361 });
362
363 die "unable to detect remote migration address\n" if !$raddr;
364
365 ## create tunnel to remote port
366 $self->log('info', "starting ssh migration tunnel");
367 my $pfamily = PVE::Tools::get_host_address_family($nodename);
368 my $lport = ($raddr eq "localhost") ? PVE::Tools::next_migrate_port($pfamily) : undef;
369 $self->{tunnel} = $self->fork_tunnel($self->{nodeip}, $lport, $rport);
370
371 my $start = time();
372 $self->log('info', "starting online/live migration on $raddr:$rport");
373 $self->{livemigration} = 1;
374
375 # load_defaults
376 my $defaults = PVE::QemuServer::load_defaults();
377
378 # always set migrate speed (overwrite kvm default of 32m)
379 # we set a very hight default of 8192m which is basically unlimited
380 my $migrate_speed = $defaults->{migrate_speed} || 8192;
381 $migrate_speed = $conf->{migrate_speed} || $migrate_speed;
382 $migrate_speed = $migrate_speed * 1048576;
383 $self->log('info', "migrate_set_speed: $migrate_speed");
384 eval {
385 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
386 };
387 $self->log('info', "migrate_set_speed error: $@") if $@;
388
389 my $migrate_downtime = $defaults->{migrate_downtime};
390 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
391 if (defined($migrate_downtime)) {
392 $self->log('info', "migrate_set_downtime: $migrate_downtime");
393 eval {
394 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
395 };
396 $self->log('info', "migrate_set_downtime error: $@") if $@;
397 }
398
399 eval {
400 PVE::QemuServer::set_migration_caps($vmid);
401 };
402 warn $@ if $@;
403
404 #set cachesize 10% of the total memory
405 my $cachesize = int($conf->{memory}*1048576/10);
406 eval {
407 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => $cachesize);
408 };
409
410 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
411 my $rpcenv = PVE::RPCEnvironment::get();
412 my $authuser = $rpcenv->get_user();
413
414 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
415
416 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
417 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
418
419 $self->log('info', "spice client_migrate_info");
420
421 eval {
422 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice',
423 hostname => $proxyticket, 'tls-port' => $spice_port,
424 'cert-subject' => $subject);
425 };
426 $self->log('info', "client_migrate_info error: $@") if $@;
427
428 }
429
430 eval {
431 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => "tcp:$raddr:$rport");
432 };
433 my $merr = $@;
434 $self->log('info', "migrate uri => tcp:$raddr:$rport failed: $merr") if $merr;
435
436 my $lstat = 0;
437 my $usleep = 2000000;
438 my $i = 0;
439 my $err_count = 0;
440 my $lastrem = undef;
441 my $downtimecounter = 0;
442 while (1) {
443 $i++;
444 my $avglstat = $lstat/$i if $lstat;
445
446 usleep($usleep);
447 my $stat;
448 eval {
449 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
450 };
451 if (my $err = $@) {
452 $err_count++;
453 warn "query migrate failed: $err\n";
454 if ($err_count <= 5) {
455 usleep(1000000);
456 next;
457 }
458 die "too many query migrate failures - aborting\n";
459 }
460
461 if ($stat->{status} =~ m/^(setup)$/im) {
462 sleep(1);
463 next;
464 }
465
466 if ($stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
467 $merr = undef;
468 $err_count = 0;
469 if ($stat->{status} eq 'completed') {
470 my $delay = time() - $start;
471 if ($delay > 0) {
472 my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
473 my $downtime = $stat->{downtime} || 0;
474 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
475 }
476 }
477
478 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
479 die "aborting\n"
480 }
481
482 if ($stat->{status} ne 'active') {
483 $self->log('info', "migration status: $stat->{status}");
484 last;
485 }
486
487 if ($stat->{ram}->{transferred} ne $lstat) {
488 my $trans = $stat->{ram}->{transferred} || 0;
489 my $rem = $stat->{ram}->{remaining} || 0;
490 my $total = $stat->{ram}->{total} || 0;
491 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
492 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
493 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
494 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
495 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
496 #reduce sleep if remainig memory if lower than the everage transfert
497 $usleep = 300000 if $avglstat && $rem < $avglstat;
498
499 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
500 "remaining ${rem}), total ${total})");
501
502 if (${xbzrlecachesize}) {
503 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
504 }
505
506 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
507 $downtimecounter++;
508 }
509 $lastrem = $rem;
510
511 if ($downtimecounter > 5) {
512 $downtimecounter = 0;
513 $migrate_downtime *= 2;
514 $self->log('info', "migrate_set_downtime: $migrate_downtime");
515 eval {
516 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
517 };
518 $self->log('info', "migrate_set_downtime error: $@") if $@;
519 }
520
521 }
522
523
524 $lstat = $stat->{ram}->{transferred};
525
526 } else {
527 die $merr if $merr;
528 die "unable to parse migration status '$stat->{status}' - aborting\n";
529 }
530 }
531 }
532
533 sub phase2_cleanup {
534 my ($self, $vmid, $err) = @_;
535
536 return if !$self->{errors};
537 $self->{phase2errors} = 1;
538
539 $self->log('info', "aborting phase 2 - cleanup resources");
540
541 $self->log('info', "migrate_cancel");
542 eval {
543 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
544 };
545 $self->log('info', "migrate_cancel error: $@") if $@;
546
547 my $conf = $self->{vmconf};
548 delete $conf->{lock};
549 eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
550 if (my $err = $@) {
551 $self->log('err', $err);
552 }
553
554 # cleanup ressources on target host
555 my $nodename = PVE::INotify::nodename();
556
557 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
558 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
559 if (my $err = $@) {
560 $self->log('err', $err);
561 $self->{errors} = 1;
562 }
563 }
564
565 sub phase3 {
566 my ($self, $vmid) = @_;
567
568 my $volids = $self->{volumes};
569 return if $self->{phase2errors};
570
571 # destroy local copies
572 foreach my $volid (@$volids) {
573 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
574 if (my $err = $@) {
575 $self->log('err', "removing local copy of '$volid' failed - $err");
576 $self->{errors} = 1;
577 last if $err =~ /^interrupted by signal$/;
578 }
579 }
580 }
581
582 sub phase3_cleanup {
583 my ($self, $vmid, $err) = @_;
584
585 my $conf = $self->{vmconf};
586 return if $self->{phase2errors};
587
588 # move config to remote node
589 my $conffile = PVE::QemuServer::config_file($vmid);
590 my $newconffile = PVE::QemuServer::config_file($vmid, $self->{node});
591
592 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
593 if !rename($conffile, $newconffile);
594
595 if ($self->{livemigration}) {
596 # now that config file is move, we can resume vm on target if livemigrate
597 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
598 eval{ PVE::Tools::run_command($cmd, outfunc => sub {},
599 errfunc => sub {
600 my $line = shift;
601 $self->log('err', $line);
602 });
603 };
604 if (my $err = $@) {
605 $self->log('err', $err);
606 $self->{errors} = 1;
607 }
608 }
609
610 eval {
611
612 my $timer = 0;
613 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
614 $self->log('info', "Waiting for spice server migration");
615 while (1) {
616 my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
617 last if int($res->{'migrated'}) == 1;
618 last if $timer > 50;
619 $timer ++;
620 usleep(200000);
621 }
622 }
623 };
624
625 # always stop local VM
626 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
627 if (my $err = $@) {
628 $self->log('err', "stopping vm failed - $err");
629 $self->{errors} = 1;
630 }
631
632 if ($self->{tunnel}) {
633 eval { finish_tunnel($self, $self->{tunnel}); };
634 if (my $err = $@) {
635 $self->log('err', $err);
636 $self->{errors} = 1;
637 }
638 }
639
640 # always deactivate volumes - avoid lvm LVs to be active on several nodes
641 eval {
642 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
643 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
644 };
645 if (my $err = $@) {
646 $self->log('err', $err);
647 $self->{errors} = 1;
648 }
649
650 # clear migrate lock
651 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
652 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
653 }
654
655 sub final_cleanup {
656 my ($self, $vmid) = @_;
657
658 # nothing to do
659 }
660
661 1;