]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
migrate: collect migration tunnel child process
[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 POSIX qw( WNOHANG );
9 use PVE::INotify;
10 use PVE::Tools;
11 use PVE::Cluster;
12 use PVE::Storage;
13 use PVE::QemuServer;
14 use Time::HiRes qw( usleep );
15 use PVE::RPCEnvironment;
16
17 use base qw(PVE::AbstractMigrate);
18
19 sub fork_command_pipe {
20 my ($self, $cmd) = @_;
21
22 my $reader = IO::File->new();
23 my $writer = IO::File->new();
24
25 my $orig_pid = $$;
26
27 my $cpid;
28
29 eval { $cpid = open2($reader, $writer, @$cmd); };
30
31 my $err = $@;
32
33 # catch exec errors
34 if ($orig_pid != $$) {
35 $self->log('err', "can't fork command pipe\n");
36 POSIX::_exit(1);
37 kill('KILL', $$);
38 }
39
40 die $err if $err;
41
42 return { writer => $writer, reader => $reader, pid => $cpid };
43 }
44
45 sub finish_command_pipe {
46 my ($self, $cmdpipe, $timeout) = @_;
47
48 my $cpid = $cmdpipe->{pid};
49 return if !defined($cpid);
50
51 my $writer = $cmdpipe->{writer};
52 my $reader = $cmdpipe->{reader};
53
54 $writer->close();
55 $reader->close();
56
57 my $collect_child_process = sub {
58 my $res = waitpid($cpid, WNOHANG);
59 if (defined($res) && ($res == $cpid)) {
60 delete $cmdpipe->{cpid};
61 return 1;
62 } else {
63 return 0;
64 }
65 };
66
67 if ($timeout) {
68 for (my $i = 0; $i < $timeout; $i++) {
69 return if &$collect_child_process();
70 sleep(1);
71 }
72 }
73
74 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
75 kill(15, $cpid);
76
77 # wait again
78 for (my $i = 0; $i < 10; $i++) {
79 return if &$collect_child_process();
80 sleep(1);
81 }
82
83 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
84 kill 9, $cpid;
85 sleep 1;
86
87 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
88 if !&$collect_child_process();
89 }
90
91 sub fork_tunnel {
92 my ($self, $nodeip, $lport, $rport) = @_;
93
94 my @localtunnelinfo = $lport ? ('-L' , "$lport:localhost:$rport" ) : ();
95
96 my $cmd = [@{$self->{rem_ssh}}, @localtunnelinfo, 'qm', 'mtunnel' ];
97
98 my $tunnel = $self->fork_command_pipe($cmd);
99
100 my $reader = $tunnel->{reader};
101
102 my $helo;
103 eval {
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$/;
109 };
110 my $err = $@;
111
112 if ($err) {
113 $self->finish_command_pipe($tunnel);
114 die "can't open migration tunnel - $err";
115 }
116 return $tunnel;
117 }
118
119 sub finish_tunnel {
120 my ($self, $tunnel) = @_;
121
122 my $writer = $tunnel->{writer};
123
124 eval {
125 PVE::Tools::run_with_timeout(30, sub {
126 print $writer "quit\n";
127 $writer->flush();
128 });
129 };
130 my $err = $@;
131
132 $self->finish_command_pipe($tunnel, 30);
133
134 die $err if $err;
135 }
136
137 sub lock_vm {
138 my ($self, $vmid, $code, @param) = @_;
139
140 return PVE::QemuConfig->lock_config($vmid, $code, @param);
141 }
142
143 sub prepare {
144 my ($self, $vmid) = @_;
145
146 my $online = $self->{opts}->{online};
147
148 $self->{storecfg} = PVE::Storage::config();
149
150 # test if VM exists
151 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
152
153 PVE::QemuConfig->check_lock($conf);
154
155 my $running = 0;
156 if (my $pid = PVE::QemuServer::check_running($vmid)) {
157 die "cant migrate running VM without --online\n" if !$online;
158 $running = $pid;
159
160 $self->{forcemachine} = PVE::QemuServer::qemu_machine_pxe($vmid, $conf);
161
162 }
163
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";
167 } else {
168 $self->log('info', "migrating VM which uses local devices");
169 }
170 }
171
172 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
173
174 my $need_activate = [];
175 foreach my $volid (@$vollist) {
176 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
177
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});
181
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);
187 } else {
188 # only activate if not shared
189 push @$need_activate, $volid;
190 }
191 }
192
193 # activate volumes
194 PVE::Storage::activate_volumes($self->{storecfg}, $need_activate);
195
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 $@;
200
201 return $running;
202 }
203
204 sub sync_disks {
205 my ($self, $vmid) = @_;
206
207 $self->log('info', "copying disk images");
208
209 my $conf = $self->{vmconf};
210
211 $self->{volumes} = [];
212
213 my $res = [];
214
215 eval {
216
217 my $volhash = {};
218 my $cdromhash = {};
219
220 my $sharedvm = 1;
221
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);
227
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) = @_;
232
233 # check if storage is available on target node
234 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
235
236 $volhash->{$volid} = 1;
237 $sharedvm = 0; # there is a non-shared disk
238 });
239 }
240
241 # and add used, owned/non-shared disks (just to be sure we have all)
242
243 PVE::QemuServer::foreach_volid($conf, sub {
244 my ($volid, $is_cdrom) = @_;
245
246 return if !$volid;
247
248 die "can't migrate local file/device '$volid'\n" if $volid =~ m|^/|;
249
250 if ($is_cdrom) {
251 die "cant migrate local cdrom drive\n" if $volid eq 'cdrom';
252 return if $volid eq 'none';
253 $cdromhash->{$volid} = 1;
254 }
255
256 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
257
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});
261
262 return if $scfg->{shared};
263
264 die "can't migrate local cdrom '$volid'\n" if $cdromhash->{$volid};
265
266 $sharedvm = 0;
267
268 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
269
270 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
271 if !$owner || ($owner != $self->{vmid});
272
273 $volhash->{$volid} = 1;
274 });
275
276 if ($self->{running} && !$sharedvm) {
277 die "can't do online migration - VM uses local disks\n";
278 }
279
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);
284
285 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
286 if (!($scfg->{type} eq 'dir' || $scfg->{type} eq 'zfspool') && (!$sharedvm));
287
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;
292 }
293 }
294
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);
299 }
300 };
301 die "Failed to sync data - $@" if $@;
302 }
303
304 sub phase1 {
305 my ($self, $vmid) = @_;
306
307 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
308
309 my $conf = $self->{vmconf};
310
311 # set migrate lock in config file
312 $conf->{lock} = 'migrate';
313 PVE::QemuConfig->write_config($vmid, $conf);
314
315 sync_disks($self, $vmid);
316
317 };
318
319 sub phase1_cleanup {
320 my ($self, $vmid, $err) = @_;
321
322 $self->log('info', "aborting phase 1 - cleanup resources");
323
324 my $conf = $self->{vmconf};
325 delete $conf->{lock};
326 eval { PVE::QemuConfig->write_config($vmid, $conf) };
327 if (my $err = $@) {
328 $self->log('err', $err);
329 }
330
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 ?
335 }
336 }
337 }
338
339 sub phase2 {
340 my ($self, $vmid) = @_;
341
342 my $conf = $self->{vmconf};
343
344 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
345
346 my $raddr;
347 my $rport;
348 my $nodename = PVE::INotify::nodename();
349
350 ## start on remote node
351 my $cmd = [@{$self->{rem_ssh}}];
352
353 my $spice_ticket;
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};
357 }
358
359 push @$cmd , 'qm', 'start', $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename;
360
361 if ($self->{forcemachine}) {
362 push @$cmd, '--machine', $self->{forcemachine};
363 }
364
365 my $spice_port;
366
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 {
370 my $line = shift;
371
372 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
373 $raddr = $1;
374 $rport = int($2);
375 }
376 elsif ($line =~ m/^migration listens on port (\d+)$/) {
377 $raddr = "localhost";
378 $rport = int($1);
379 }
380 elsif ($line =~ m/^spice listens on port (\d+)$/) {
381 $spice_port = int($1);
382 }
383 }, errfunc => sub {
384 my $line = shift;
385 $self->log('info', $line);
386 });
387
388 die "unable to detect remote migration address\n" if !$raddr;
389
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);
395
396 my $start = time();
397 $self->log('info', "starting online/live migration on $raddr:$rport");
398 $self->{livemigration} = 1;
399
400 # load_defaults
401 my $defaults = PVE::QemuServer::load_defaults();
402
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");
409 eval {
410 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
411 };
412 $self->log('info', "migrate_set_speed error: $@") if $@;
413
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");
418 eval {
419 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
420 };
421 $self->log('info', "migrate_set_downtime error: $@") if $@;
422 }
423
424 eval {
425 PVE::QemuServer::set_migration_caps($vmid);
426 };
427 warn $@ if $@;
428
429 #set cachesize 10% of the total memory
430 my $cachesize = int($conf->{memory}*1048576/10);
431 eval {
432 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => $cachesize);
433 };
434
435 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
436 my $rpcenv = PVE::RPCEnvironment::get();
437 my $authuser = $rpcenv->get_user();
438
439 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
440
441 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
442 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
443
444 $self->log('info', "spice client_migrate_info");
445
446 eval {
447 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice',
448 hostname => $proxyticket, 'tls-port' => $spice_port,
449 'cert-subject' => $subject);
450 };
451 $self->log('info', "client_migrate_info error: $@") if $@;
452
453 }
454
455 eval {
456 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => "tcp:$raddr:$rport");
457 };
458 my $merr = $@;
459 $self->log('info', "migrate uri => tcp:$raddr:$rport failed: $merr") if $merr;
460
461 my $lstat = 0;
462 my $usleep = 2000000;
463 my $i = 0;
464 my $err_count = 0;
465 my $lastrem = undef;
466 my $downtimecounter = 0;
467 while (1) {
468 $i++;
469 my $avglstat = $lstat/$i if $lstat;
470
471 usleep($usleep);
472 my $stat;
473 eval {
474 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
475 };
476 if (my $err = $@) {
477 $err_count++;
478 warn "query migrate failed: $err\n";
479 if ($err_count <= 5) {
480 usleep(1000000);
481 next;
482 }
483 die "too many query migrate failures - aborting\n";
484 }
485
486 if ($stat->{status} =~ m/^(setup)$/im) {
487 sleep(1);
488 next;
489 }
490
491 if ($stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
492 $merr = undef;
493 $err_count = 0;
494 if ($stat->{status} eq 'completed') {
495 my $delay = time() - $start;
496 if ($delay > 0) {
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");
500 }
501 }
502
503 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
504 die "aborting\n"
505 }
506
507 if ($stat->{status} ne 'active') {
508 $self->log('info', "migration status: $stat->{status}");
509 last;
510 }
511
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;
523
524 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
525 "remaining ${rem}), total ${total})");
526
527 if (${xbzrlecachesize}) {
528 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
529 }
530
531 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
532 $downtimecounter++;
533 }
534 $lastrem = $rem;
535
536 if ($downtimecounter > 5) {
537 $downtimecounter = 0;
538 $migrate_downtime *= 2;
539 $self->log('info', "migrate_set_downtime: $migrate_downtime");
540 eval {
541 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
542 };
543 $self->log('info', "migrate_set_downtime error: $@") if $@;
544 }
545
546 }
547
548
549 $lstat = $stat->{ram}->{transferred};
550
551 } else {
552 die $merr if $merr;
553 die "unable to parse migration status '$stat->{status}' - aborting\n";
554 }
555 }
556 #to be sure tat the tunnel is closed
557 if ($self->{tunnel}) {
558 eval { finish_tunnel($self, $self->{tunnel}); };
559 if (my $err = $@) {
560 $self->log('err', $err);
561 $self->{errors} = 1;
562 }
563 }
564 }
565
566 sub phase2_cleanup {
567 my ($self, $vmid, $err) = @_;
568
569 return if !$self->{errors};
570 $self->{phase2errors} = 1;
571
572 $self->log('info', "aborting phase 2 - cleanup resources");
573
574 $self->log('info', "migrate_cancel");
575 eval {
576 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
577 };
578 $self->log('info', "migrate_cancel error: $@") if $@;
579
580 my $conf = $self->{vmconf};
581 delete $conf->{lock};
582 eval { PVE::QemuConfig->write_config($vmid, $conf) };
583 if (my $err = $@) {
584 $self->log('err', $err);
585 }
586
587 # cleanup ressources on target host
588 my $nodename = PVE::INotify::nodename();
589
590 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
591 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
592 if (my $err = $@) {
593 $self->log('err', $err);
594 $self->{errors} = 1;
595 }
596
597 if ($self->{tunnel}) {
598 eval { finish_tunnel($self, $self->{tunnel}); };
599 if (my $err = $@) {
600 $self->log('err', $err);
601 $self->{errors} = 1;
602 }
603 }
604 }
605
606 sub phase3 {
607 my ($self, $vmid) = @_;
608
609 my $volids = $self->{volumes};
610 return if $self->{phase2errors};
611
612 # destroy local copies
613 foreach my $volid (@$volids) {
614 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
615 if (my $err = $@) {
616 $self->log('err', "removing local copy of '$volid' failed - $err");
617 $self->{errors} = 1;
618 last if $err =~ /^interrupted by signal$/;
619 }
620 }
621 }
622
623 sub phase3_cleanup {
624 my ($self, $vmid, $err) = @_;
625
626 my $conf = $self->{vmconf};
627 return if $self->{phase2errors};
628
629 # move config to remote node
630 my $conffile = PVE::QemuConfig->config_file($vmid);
631 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
632
633 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
634 if !rename($conffile, $newconffile);
635
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 {},
640 errfunc => sub {
641 my $line = shift;
642 $self->log('err', $line);
643 });
644 };
645 if (my $err = $@) {
646 $self->log('err', $err);
647 $self->{errors} = 1;
648 }
649 }
650
651 eval {
652
653 my $timer = 0;
654 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
655 $self->log('info', "Waiting for spice server migration");
656 while (1) {
657 my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
658 last if int($res->{'migrated'}) == 1;
659 last if $timer > 50;
660 $timer ++;
661 usleep(200000);
662 }
663 }
664 };
665
666 # always stop local VM
667 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
668 if (my $err = $@) {
669 $self->log('err', "stopping vm failed - $err");
670 $self->{errors} = 1;
671 }
672
673 # always deactivate volumes - avoid lvm LVs to be active on several nodes
674 eval {
675 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
676 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
677 };
678 if (my $err = $@) {
679 $self->log('err', $err);
680 $self->{errors} = 1;
681 }
682
683 # clear migrate lock
684 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
685 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
686 }
687
688 sub final_cleanup {
689 my ($self, $vmid) = @_;
690
691 # nothing to do
692 }
693
694 1;