]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
new vga_conf_has_spice() helper
[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 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
318 my $res = PVE::QemuServer::vm_mon_cmd($vmid, 'query-spice');
319 push @$cmd, 'SPICETICKET='.$res->{ticket} if $res->{ticket};
320 }
321
322 push @$cmd , 'qm', 'start', $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename;
323
324
325 if ($self->{forcemachine}) {
326 push @$cmd, '--machine', $self->{forcemachine};
327 }
328
329 my $spice_port;
330
331 PVE::Tools::run_command($cmd, outfunc => sub {
332 my $line = shift;
333
334 if ($line =~ m/^migration listens on port (\d+)$/) {
335 $rport = int($1);
336 }elsif ($line =~ m/^spice listens on port (\d+)$/) {
337 $spice_port = int($1);
338 }
339 }, errfunc => sub {
340 my $line = shift;
341 $self->log('info', $line);
342 });
343
344 die "unable to detect remote migration port\n" if !$rport;
345
346 $self->log('info', "starting migration tunnel");
347
348 ## create tunnel to remote port
349 my $lport = PVE::Tools::next_migrate_port();
350 $self->{tunnel} = $self->fork_tunnel($self->{nodeip}, $lport, $rport);
351
352 $self->log('info', "starting online/live migration on port $lport");
353 # start migration
354
355 my $start = time();
356
357 # load_defaults
358 my $defaults = PVE::QemuServer::load_defaults();
359
360 # always set migrate speed (overwrite kvm default of 32m)
361 # we set a very hight default of 8192m which is basically unlimited
362 my $migrate_speed = $defaults->{migrate_speed} || 8192;
363 $migrate_speed = $conf->{migrate_speed} || $migrate_speed;
364 $migrate_speed = $migrate_speed * 1048576;
365 $self->log('info', "migrate_set_speed: $migrate_speed");
366 eval {
367 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
368 };
369 $self->log('info', "migrate_set_speed error: $@") if $@;
370
371 my $migrate_downtime = $defaults->{migrate_downtime};
372 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
373 if (defined($migrate_downtime)) {
374 $self->log('info', "migrate_set_downtime: $migrate_downtime");
375 eval {
376 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
377 };
378 $self->log('info', "migrate_set_downtime error: $@") if $@;
379 }
380
381 my $capabilities = {};
382 $capabilities->{capability} = "xbzrle";
383 $capabilities->{state} = JSON::false;
384
385 eval {
386 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-capabilities", capabilities => [$capabilities]);
387 };
388
389 #set cachesize 10% of the total memory
390 my $cachesize = int($conf->{memory}*1048576/10);
391 eval {
392 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => $cachesize);
393 };
394
395 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
396 my $rpcenv = PVE::RPCEnvironment::get();
397 my $authuser = $rpcenv->get_user();
398
399 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
400
401 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
402 my $subject = PVE::QemuServer::read_x509_subject_spice($filename);
403
404 $self->log('info', "spice client_migrate_info");
405
406 eval {
407 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice',
408 hostname => $proxyticket, 'tls-port' => $spice_port,
409 'cert-subject' => $subject);
410 };
411 $self->log('info', "client_migrate_info error: $@") if $@;
412
413 }
414
415 eval {
416 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => "tcp:localhost:$lport");
417 };
418 my $merr = $@;
419
420 my $lstat = 0;
421 my $usleep = 2000000;
422 my $i = 0;
423 my $err_count = 0;
424 my $lastrem = undef;
425 my $downtimecounter = 0;
426 while (1) {
427 $i++;
428 my $avglstat = $lstat/$i if $lstat;
429
430 usleep($usleep);
431 my $stat;
432 eval {
433 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
434 };
435 if (my $err = $@) {
436 $err_count++;
437 warn "query migrate failed: $err\n";
438 if ($err_count <= 5) {
439 usleep(1000000);
440 next;
441 }
442 die "too many query migrate failures - aborting\n";
443 }
444 if ($stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
445 $merr = undef;
446 $err_count = 0;
447 if ($stat->{status} eq 'completed') {
448 my $delay = time() - $start;
449 if ($delay > 0) {
450 my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
451 my $downtime = $stat->{downtime} || 0;
452 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
453 }
454 }
455
456 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
457 die "aborting\n"
458 }
459
460 if ($stat->{status} ne 'active') {
461 $self->log('info', "migration status: $stat->{status}");
462 last;
463 }
464
465 if ($stat->{ram}->{transferred} ne $lstat) {
466 my $trans = $stat->{ram}->{transferred} || 0;
467 my $rem = $stat->{ram}->{remaining} || 0;
468 my $total = $stat->{ram}->{total} || 0;
469 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
470 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
471 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
472 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
473 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
474 #reduce sleep if remainig memory if lower than the everage transfert
475 $usleep = 300000 if $avglstat && $rem < $avglstat;
476
477 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
478 "remaining ${rem}), total ${total})");
479
480 #$self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
481 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
482 $downtimecounter++;
483 }
484 $lastrem = $rem;
485
486 if ($downtimecounter > 5) {
487 $downtimecounter = 0;
488 $migrate_downtime *= 2;
489 $self->log('info', "migrate_set_downtime: $migrate_downtime");
490 eval {
491 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
492 };
493 $self->log('info', "migrate_set_downtime error: $@") if $@;
494 }
495
496 }
497
498
499 $lstat = $stat->{ram}->{transferred};
500
501 } else {
502 die $merr if $merr;
503 die "unable to parse migration status '$stat->{status}' - aborting\n";
504 }
505 }
506 }
507
508 sub phase2_cleanup {
509 my ($self, $vmid, $err) = @_;
510
511 return if !$self->{errors};
512 $self->{phase2errors} = 1;
513
514 $self->log('info', "aborting phase 2 - cleanup resources");
515
516 $self->log('info', "migrate_cancel");
517 eval {
518 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
519 };
520 $self->log('info', "migrate_cancel error: $@") if $@;
521
522 my $conf = $self->{vmconf};
523 delete $conf->{lock};
524 eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
525 if (my $err = $@) {
526 $self->log('err', $err);
527 }
528
529 # cleanup ressources on target host
530 my $nodename = PVE::INotify::nodename();
531
532 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
533 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
534 if (my $err = $@) {
535 $self->log('err', $err);
536 $self->{errors} = 1;
537 }
538 }
539
540 sub phase3 {
541 my ($self, $vmid) = @_;
542
543 my $volids = $self->{volumes};
544 return if $self->{phase2errors};
545
546 # destroy local copies
547 foreach my $volid (@$volids) {
548 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
549 if (my $err = $@) {
550 $self->log('err', "removing local copy of '$volid' failed - $err");
551 $self->{errors} = 1;
552 last if $err =~ /^interrupted by signal$/;
553 }
554 }
555 }
556
557 sub phase3_cleanup {
558 my ($self, $vmid, $err) = @_;
559
560 my $conf = $self->{vmconf};
561 return if $self->{phase2errors};
562
563 # move config to remote node
564 my $conffile = PVE::QemuServer::config_file($vmid);
565 my $newconffile = PVE::QemuServer::config_file($vmid, $self->{node});
566
567 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
568 if !rename($conffile, $newconffile);
569
570 # now that config file is move, we can resume vm on target if livemigrate
571 if ($self->{tunnel}) {
572 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock'];
573 eval{ PVE::Tools::run_command($cmd, outfunc => sub {},
574 errfunc => sub {
575 my $line = shift;
576 $self->log('err', $line);
577 });
578 };
579 if (my $err = $@) {
580 $self->log('err', $err);
581 $self->{errors} = 1;
582 }
583 }
584
585 my $timer = 0;
586 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
587 $self->log('info', "Waiting for spice server migration");
588 while (1) {
589 my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
590 last if int($res->{'migrated'}) == 1;
591 last if $timer > 50;
592 $timer ++;
593 usleep(200000);
594 }
595 }
596
597 # always stop local VM
598 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
599 if (my $err = $@) {
600 $self->log('err', "stopping vm failed - $err");
601 $self->{errors} = 1;
602 }
603
604 if ($self->{tunnel}) {
605 eval { finish_tunnel($self, $self->{tunnel}); };
606 if (my $err = $@) {
607 $self->log('err', $err);
608 $self->{errors} = 1;
609 }
610 }
611
612 # always deactivate volumes - avoid lvm LVs to be active on several nodes
613 eval {
614 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
615 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
616 };
617 if (my $err = $@) {
618 $self->log('err', $err);
619 $self->{errors} = 1;
620 }
621
622 # clear migrate lock
623 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
624 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
625 }
626
627 sub final_cleanup {
628 my ($self, $vmid) = @_;
629
630 # nothing to do
631 }
632
633 1;