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