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