]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
PVE::QemuMigrate. do not use JSON - not required here
[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 use PVE::ReplicationConfig;
17 use PVE::ReplicationState;
18 use PVE::Replication;
19
20 use base qw(PVE::AbstractMigrate);
21
22 sub fork_command_pipe {
23 my ($self, $cmd) = @_;
24
25 my $reader = IO::File->new();
26 my $writer = IO::File->new();
27
28 my $orig_pid = $$;
29
30 my $cpid;
31
32 eval { $cpid = open2($reader, $writer, @$cmd); };
33
34 my $err = $@;
35
36 # catch exec errors
37 if ($orig_pid != $$) {
38 $self->log('err', "can't fork command pipe\n");
39 POSIX::_exit(1);
40 kill('KILL', $$);
41 }
42
43 die $err if $err;
44
45 return { writer => $writer, reader => $reader, pid => $cpid };
46 }
47
48 sub finish_command_pipe {
49 my ($self, $cmdpipe, $timeout) = @_;
50
51 my $cpid = $cmdpipe->{pid};
52 return if !defined($cpid);
53
54 my $writer = $cmdpipe->{writer};
55 my $reader = $cmdpipe->{reader};
56
57 $writer->close();
58 $reader->close();
59
60 my $collect_child_process = sub {
61 my $res = waitpid($cpid, WNOHANG);
62 if (defined($res) && ($res == $cpid)) {
63 delete $cmdpipe->{cpid};
64 return 1;
65 } else {
66 return 0;
67 }
68 };
69
70 if ($timeout) {
71 for (my $i = 0; $i < $timeout; $i++) {
72 return if &$collect_child_process();
73 sleep(1);
74 }
75 }
76
77 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
78 kill(15, $cpid);
79
80 # wait again
81 for (my $i = 0; $i < 10; $i++) {
82 return if &$collect_child_process();
83 sleep(1);
84 }
85
86 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
87 kill 9, $cpid;
88 sleep 1;
89
90 $self->log('err', "ssh tunnel child process (PID $cpid) couldn't be collected\n")
91 if !&$collect_child_process();
92 }
93
94 sub fork_tunnel {
95 my ($self, $tunnel_addr) = @_;
96
97 my @localtunnelinfo = defined($tunnel_addr) ? ('-L' , $tunnel_addr ) : ();
98
99 my $cmd = [@{$self->{rem_ssh}}, '-o ExitOnForwardFailure=yes', @localtunnelinfo, 'qm', 'mtunnel' ];
100
101 my $tunnel = $self->fork_command_pipe($cmd);
102
103 my $reader = $tunnel->{reader};
104
105 my $helo;
106 eval {
107 PVE::Tools::run_with_timeout(60, sub { $helo = <$reader>; });
108 die "no reply\n" if !$helo;
109 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
110 die "got strange reply from mtunnel ('$helo')\n"
111 if $helo !~ m/^tunnel online$/;
112 };
113 my $err = $@;
114
115 if ($err) {
116 $self->finish_command_pipe($tunnel);
117 die "can't open migration tunnel - $err";
118 }
119 return $tunnel;
120 }
121
122 sub finish_tunnel {
123 my ($self, $tunnel) = @_;
124
125 my $writer = $tunnel->{writer};
126
127 eval {
128 PVE::Tools::run_with_timeout(30, sub {
129 print $writer "quit\n";
130 $writer->flush();
131 });
132 };
133 my $err = $@;
134
135 $self->finish_command_pipe($tunnel, 30);
136
137 if ($tunnel->{sock_addr}) {
138 # ssh does not clean up on local host
139 my $cmd = ['rm', '-f', $tunnel->{sock_addr}]; #
140 PVE::Tools::run_command($cmd);
141
142 # .. and just to be sure check on remote side
143 unshift @{$cmd}, @{$self->{rem_ssh}};
144 PVE::Tools::run_command($cmd);
145 }
146
147 die $err if $err;
148 }
149
150 sub lock_vm {
151 my ($self, $vmid, $code, @param) = @_;
152
153 return PVE::QemuConfig->lock_config($vmid, $code, @param);
154 }
155
156 sub prepare {
157 my ($self, $vmid) = @_;
158
159 my $online = $self->{opts}->{online};
160
161 $self->{storecfg} = PVE::Storage::config();
162
163 # test if VM exists
164 my $conf = $self->{vmconf} = PVE::QemuConfig->load_config($vmid);
165
166 PVE::QemuConfig->check_lock($conf);
167
168 my $running = 0;
169 if (my $pid = PVE::QemuServer::check_running($vmid)) {
170 die "can't migrate running VM without --online\n" if !$online;
171 $running = $pid;
172
173 $self->{forcemachine} = PVE::QemuServer::qemu_machine_pxe($vmid, $conf);
174
175 }
176
177 if (my $loc_res = PVE::QemuServer::check_local_resources($conf, 1)) {
178 if ($self->{running} || !$self->{opts}->{force}) {
179 die "can't migrate VM which uses local devices\n";
180 } else {
181 $self->log('info', "migrating VM which uses local devices");
182 }
183 }
184
185 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
186
187 my $need_activate = [];
188 foreach my $volid (@$vollist) {
189 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
190
191 # check if storage is available on both nodes
192 my $targetsid = $self->{opts}->{targetstorage} ? $self->{opts}->{targetstorage} : $sid;
193
194 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
195 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
196
197 if ($scfg->{shared}) {
198 # PVE::Storage::activate_storage checks this for non-shared storages
199 my $plugin = PVE::Storage::Plugin->lookup($scfg->{type});
200 warn "Used shared storage '$sid' is not online on source node!\n"
201 if !$plugin->check_connection($sid, $scfg);
202 } else {
203 # only activate if not shared
204 push @$need_activate, $volid;
205 }
206 }
207
208 # activate volumes
209 PVE::Storage::activate_volumes($self->{storecfg}, $need_activate);
210
211 # test ssh connection
212 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
213 eval { $self->cmd_quiet($cmd); };
214 die "Can't connect to destination address using public key\n" if $@;
215
216 return $running;
217 }
218
219 sub sync_disks {
220 my ($self, $vmid) = @_;
221
222 my $conf = $self->{vmconf};
223
224 # local volumes which have been copied
225 $self->{volumes} = [];
226
227 my $res = [];
228
229 eval {
230
231 # found local volumes and their origin
232 my $local_volumes = {};
233 my $local_volumes_errors = {};
234 my $other_errors = [];
235 my $abort = 0;
236
237 my $sharedvm = 1;
238
239 my $log_error = sub {
240 my ($msg, $volid) = @_;
241
242 if (defined($volid)) {
243 $local_volumes_errors->{$volid} = $msg;
244 } else {
245 push @$other_errors, $msg;
246 }
247 $abort = 1;
248 };
249
250 my @sids = PVE::Storage::storage_ids($self->{storecfg});
251 foreach my $storeid (@sids) {
252 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
253 next if $scfg->{shared};
254 next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
255
256 # get list from PVE::Storage (for unused volumes)
257 my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
258
259 next if @{$dl->{$storeid}} == 0;
260
261 my $targetsid = $self->{opts}->{targetstorage} ? $self->{opts}->{targetstorage} : $storeid;
262
263 # check if storage is available on target node
264 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
265 $sharedvm = 0; # there is a non-shared disk
266
267 PVE::Storage::foreach_volid($dl, sub {
268 my ($volid, $sid, $volname) = @_;
269
270 $local_volumes->{$volid} = 'storage';
271 });
272 }
273
274 my $test_volid = sub {
275 my ($volid, $attr) = @_;
276
277 if ($volid =~ m|^/|) {
278 $local_volumes->{$volid} = 'config';
279 die "local file/device\n";
280 }
281
282 my $snaprefs = $attr->{referenced_in_snapshot};
283
284 if ($attr->{cdrom}) {
285 if ($volid eq 'cdrom') {
286 my $msg = "can't migrate local cdrom drive";
287 if (defined($snaprefs) && !$attr->{referenced_in_config}) {
288 my $snapnames = join(', ', sort keys %$snaprefs);
289 $msg .= " (referenced in snapshot - $snapnames)";
290 }
291 &$log_error("$msg\n");
292 return;
293 }
294 return if $volid eq 'none';
295 }
296
297 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
298
299 my $targetsid = $self->{opts}->{targetstorage} ? $self->{opts}->{targetstorage} : $sid;
300 # check if storage is available on both nodes
301 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
302 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
303
304 return if $scfg->{shared};
305
306 $sharedvm = 0;
307
308 $local_volumes->{$volid} = $attr->{referenced_in_config} ? 'config' : 'snapshot';
309
310 die "local cdrom image\n" if $attr->{cdrom};
311
312 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
313
314 die "owned by other VM (owner = VM $owner)\n"
315 if !$owner || ($owner != $self->{vmid});
316
317 if (defined($snaprefs)) {
318 # we cannot migrate shapshots on local storage
319 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
320
321 my $format = PVE::QemuServer::qemu_img_format($scfg, $volname);
322 die "online storage migration not possible if snapshot exists\n" if $self->{running};
323 if (!($scfg->{type} eq 'zfspool' || $format eq 'qcow2')) {
324 die "non-migratable snapshot exists\n";
325 }
326 }
327
328 die "referenced by linked clone(s)\n"
329 if PVE::Storage::volume_is_base_and_used($self->{storecfg}, $volid);
330 };
331
332 PVE::QemuServer::foreach_volid($conf, sub {
333 my ($volid, $attr) = @_;
334 eval { $test_volid->($volid, $attr); };
335 if (my $err = $@) {
336 &$log_error($err, $volid);
337 }
338 });
339
340 foreach my $vol (sort keys %$local_volumes) {
341 if ($local_volumes->{$vol} eq 'storage') {
342 $self->log('info', "found local disk '$vol' (via storage)\n");
343 } elsif ($local_volumes->{$vol} eq 'config') {
344 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
345 if $self->{running} && !$self->{opts}->{"with-local-disks"};
346 $self->log('info', "found local disk '$vol' (in current VM config)\n");
347 } elsif ($local_volumes->{$vol} eq 'snapshot') {
348 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
349 } else {
350 $self->log('info', "found local disk '$vol'\n");
351 }
352 }
353
354 foreach my $vol (sort keys %$local_volumes_errors) {
355 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
356 }
357 foreach my $err (@$other_errors) {
358 $self->log('warn', "$err");
359 }
360
361 if ($self->{running} && !$sharedvm && !$self->{opts}->{targetstorage}) {
362 $self->{opts}->{targetstorage} = 1; #use same sid for remote local
363 }
364
365 if ($abort) {
366 die "can't migrate VM - check log\n";
367 }
368
369 # additional checks for local storage
370 foreach my $volid (keys %$local_volumes) {
371 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
372 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $sid);
373
374 my $migratable = ($scfg->{type} eq 'dir') || ($scfg->{type} eq 'zfspool') ||
375 ($scfg->{type} eq 'lvmthin') || ($scfg->{type} eq 'lvm');
376
377 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
378 if !$migratable;
379
380 # image is a linked clone on local storage, se we can't migrate.
381 if (my $basename = (PVE::Storage::parse_volname($self->{storecfg}, $volid))[3]) {
382 die "can't migrate '$volid' as it's a clone of '$basename'";
383 }
384 }
385
386 my $rep_volumes;
387
388 $self->log('info', "copying disk images");
389
390 my $rep_cfg = PVE::ReplicationConfig->new();
391
392 if (my $jobcfg = $rep_cfg->find_local_replication_job($vmid, $self->{node})) {
393 die "can't live migrate VM with replicated volumes\n" if $self->{running};
394 my $start_time = time();
395 my $logfunc = sub { my ($msg) = @_; $self->log('info', $msg); };
396 $rep_volumes = PVE::Replication::run_replication(
397 'PVE::QemuConfig', $jobcfg, $start_time, $start_time, $logfunc);
398 }
399
400 foreach my $volid (keys %$local_volumes) {
401 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
402 if ($self->{running} && $self->{opts}->{targetstorage} && $local_volumes->{$volid} eq 'config') {
403 push @{$self->{online_local_volumes}}, $volid;
404 } else {
405 next if $rep_volumes->{$volid};
406 push @{$self->{volumes}}, $volid;
407 my $insecure = $self->{opts}->{migration_type} eq 'insecure';
408 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{ssh_info}, $sid,
409 undef, undef, undef, undef, $insecure);
410 }
411 }
412 };
413 die "Failed to sync data - $@" if $@;
414 }
415
416 sub cleanup_remotedisks {
417 my ($self) = @_;
418
419 foreach my $target_drive (keys %{$self->{target_drive}}) {
420
421 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{volid});
422 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
423
424 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
425
426 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
427 if (my $err = $@) {
428 $self->log('err', $err);
429 $self->{errors} = 1;
430 }
431 }
432 }
433
434 sub phase1 {
435 my ($self, $vmid) = @_;
436
437 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
438
439 my $conf = $self->{vmconf};
440
441 # set migrate lock in config file
442 $conf->{lock} = 'migrate';
443 PVE::QemuConfig->write_config($vmid, $conf);
444
445 sync_disks($self, $vmid);
446
447 };
448
449 sub phase1_cleanup {
450 my ($self, $vmid, $err) = @_;
451
452 $self->log('info', "aborting phase 1 - cleanup resources");
453
454 my $conf = $self->{vmconf};
455 delete $conf->{lock};
456 eval { PVE::QemuConfig->write_config($vmid, $conf) };
457 if (my $err = $@) {
458 $self->log('err', $err);
459 }
460
461 if ($self->{volumes}) {
462 foreach my $volid (@{$self->{volumes}}) {
463 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
464 # fixme: try to remove ?
465 }
466 }
467 }
468
469 sub phase2 {
470 my ($self, $vmid) = @_;
471
472 my $conf = $self->{vmconf};
473
474 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
475
476 my $raddr;
477 my $rport;
478 my $ruri; # the whole migration dst. URI (protocol:address[:port])
479 my $nodename = PVE::INotify::nodename();
480
481 ## start on remote node
482 my $cmd = [@{$self->{rem_ssh}}];
483
484 my $spice_ticket;
485 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
486 my $res = PVE::QemuServer::vm_mon_cmd($vmid, 'query-spice');
487 $spice_ticket = $res->{ticket};
488 }
489
490 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
491
492 my $migration_type = $self->{opts}->{migration_type};
493
494 push @$cmd, '--migration_type', $migration_type;
495
496 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
497 if $self->{opts}->{migration_network};
498
499 if ($migration_type eq 'insecure') {
500 push @$cmd, '--stateuri', 'tcp';
501 } else {
502 push @$cmd, '--stateuri', 'unix';
503 }
504
505 if ($self->{forcemachine}) {
506 push @$cmd, '--machine', $self->{forcemachine};
507 }
508
509 if ($self->{opts}->{targetstorage}) {
510 push @$cmd, '--targetstorage', $self->{opts}->{targetstorage};
511 }
512
513 my $spice_port;
514
515 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
516 # instead we pipe it through STDIN
517 PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
518 my $line = shift;
519
520 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
521 $raddr = $1;
522 $rport = int($2);
523 $ruri = "tcp:$raddr:$rport";
524 }
525 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
526 $raddr = $1;
527 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
528 $ruri = "unix:$raddr";
529 }
530 elsif ($line =~ m/^migration listens on port (\d+)$/) {
531 $raddr = "localhost";
532 $rport = int($1);
533 $ruri = "tcp:$raddr:$rport";
534 }
535 elsif ($line =~ m/^spice listens on port (\d+)$/) {
536 $spice_port = int($1);
537 }
538 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
539 my $volid = $4;
540 my $nbd_uri = "nbd:$1:$2:exportname=$3";
541 my $targetdrive = $3;
542 $targetdrive =~ s/drive-//g;
543
544 $self->{target_drive}->{$targetdrive}->{volid} = $volid;
545 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
546
547 }
548 }, errfunc => sub {
549 my $line = shift;
550 $self->log('info', $line);
551 });
552
553 die "unable to detect remote migration address\n" if !$raddr;
554
555 if ($migration_type eq 'secure') {
556 $self->log('info', "start remote tunnel");
557
558 if ($ruri =~ /^unix:/) {
559 unlink $raddr;
560 $self->{tunnel} = $self->fork_tunnel("$raddr:$raddr");
561 $self->{tunnel}->{sock_addr} = $raddr;
562
563 my $unix_socket_try = 0; # wait for the socket to become ready
564 while (! -S $raddr) {
565 $unix_socket_try++;
566 if ($unix_socket_try > 100) {
567 $self->{errors} = 1;
568 $self->finish_tunnel($self->{tunnel});
569 die "Timeout, migration socket $ruri did not get ready";
570 }
571
572 usleep(50000);
573 }
574
575 } elsif ($ruri =~ /^tcp:/) {
576 my $tunnel_addr;
577 if ($raddr eq "localhost") {
578 # for backwards compatibility with older qemu-server versions
579 my $pfamily = PVE::Tools::get_host_address_family($nodename);
580 my $lport = PVE::Tools::next_migrate_port($pfamily);
581 $tunnel_addr = "$lport:localhost:$rport";
582 }
583
584 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
585
586 } else {
587 die "unsupported protocol in migration URI: $ruri\n";
588 }
589 }
590
591 my $start = time();
592
593 if ($self->{opts}->{targetstorage} && defined($self->{online_local_volumes})) {
594 $self->{storage_migration} = 1;
595 $self->{storage_migration_jobs} = {};
596 $self->log('info', "starting storage migration");
597
598 die "The number of local disks does not match between the source and the destination.\n"
599 if (scalar(keys %{$self->{target_drive}}) != scalar @{$self->{online_local_volumes}});
600 foreach my $drive (keys %{$self->{target_drive}}){
601 my $nbd_uri = $self->{target_drive}->{$drive}->{nbd_uri};
602 $self->log('info', "$drive: start migration to to $nbd_uri");
603 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 1);
604 }
605 }
606
607 $self->log('info', "starting online/live migration on $ruri");
608 $self->{livemigration} = 1;
609
610 # load_defaults
611 my $defaults = PVE::QemuServer::load_defaults();
612
613 # always set migrate speed (overwrite kvm default of 32m)
614 # we set a very hight default of 8192m which is basically unlimited
615 my $migrate_speed = $defaults->{migrate_speed} || 8192;
616 $migrate_speed = $conf->{migrate_speed} || $migrate_speed;
617 $migrate_speed = $migrate_speed * 1048576;
618 $self->log('info', "migrate_set_speed: $migrate_speed");
619 eval {
620 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_speed", value => int($migrate_speed));
621 };
622 $self->log('info', "migrate_set_speed error: $@") if $@;
623
624 my $migrate_downtime = $defaults->{migrate_downtime};
625 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
626 if (defined($migrate_downtime)) {
627 $self->log('info', "migrate_set_downtime: $migrate_downtime");
628 eval {
629 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
630 };
631 $self->log('info', "migrate_set_downtime error: $@") if $@;
632 }
633
634 $self->log('info', "set migration_caps");
635 eval {
636 PVE::QemuServer::set_migration_caps($vmid);
637 };
638 warn $@ if $@;
639
640 #set cachesize 10% of the total memory
641 my $cachesize = int($conf->{memory}*1048576/10);
642 $self->log('info', "set cachesize: $cachesize");
643 eval {
644 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => int($cachesize));
645 };
646 $self->log('info', "migrate-set-cache-size error: $@") if $@;
647
648 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
649 my $rpcenv = PVE::RPCEnvironment::get();
650 my $authuser = $rpcenv->get_user();
651
652 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
653
654 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
655 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
656
657 $self->log('info', "spice client_migrate_info");
658
659 eval {
660 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "client_migrate_info", protocol => 'spice',
661 hostname => $proxyticket, 'tls-port' => $spice_port,
662 'cert-subject' => $subject);
663 };
664 $self->log('info', "client_migrate_info error: $@") if $@;
665
666 }
667
668 $self->log('info', "start migrate command to $ruri");
669 eval {
670 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => $ruri);
671 };
672 my $merr = $@;
673 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
674
675 my $lstat = 0;
676 my $usleep = 2000000;
677 my $i = 0;
678 my $err_count = 0;
679 my $lastrem = undef;
680 my $downtimecounter = 0;
681 while (1) {
682 $i++;
683 my $avglstat = $lstat/$i if $lstat;
684
685 usleep($usleep);
686 my $stat;
687 eval {
688 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
689 };
690 if (my $err = $@) {
691 $err_count++;
692 warn "query migrate failed: $err\n";
693 $self->log('info', "query migrate failed: $err");
694 if ($err_count <= 5) {
695 usleep(1000000);
696 next;
697 }
698 die "too many query migrate failures - aborting\n";
699 }
700
701 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
702 sleep(1);
703 next;
704 }
705
706 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
707 $merr = undef;
708 $err_count = 0;
709 if ($stat->{status} eq 'completed') {
710 my $delay = time() - $start;
711 if ($delay > 0) {
712 my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
713 my $downtime = $stat->{downtime} || 0;
714 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
715 }
716 }
717
718 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
719 $self->log('info', "migration status error: $stat->{status}");
720 die "aborting\n"
721 }
722
723 if ($stat->{status} ne 'active') {
724 $self->log('info', "migration status: $stat->{status}");
725 last;
726 }
727
728 if ($stat->{ram}->{transferred} ne $lstat) {
729 my $trans = $stat->{ram}->{transferred} || 0;
730 my $rem = $stat->{ram}->{remaining} || 0;
731 my $total = $stat->{ram}->{total} || 0;
732 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
733 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
734 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
735 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
736 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
737 #reduce sleep if remainig memory if lower than the everage transfert
738 $usleep = 300000 if $avglstat && $rem < $avglstat;
739
740 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
741 "remaining ${rem}), total ${total})");
742
743 if (${xbzrlecachesize}) {
744 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
745 }
746
747 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
748 $downtimecounter++;
749 }
750 $lastrem = $rem;
751
752 if ($downtimecounter > 5) {
753 $downtimecounter = 0;
754 $migrate_downtime *= 2;
755 $self->log('info', "migrate_set_downtime: $migrate_downtime");
756 eval {
757 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
758 };
759 $self->log('info', "migrate_set_downtime error: $@") if $@;
760 }
761
762 }
763
764
765 $lstat = $stat->{ram}->{transferred};
766
767 } else {
768 die $merr if $merr;
769 die "unable to parse migration status '$stat->{status}' - aborting\n";
770 }
771 }
772
773 # just to be sure that the tunnel gets closed on successful migration, on error
774 # phase2_cleanup closes it *after* stopping the remote waiting VM
775 if (!$self->{errors} && $self->{tunnel}) {
776 eval { finish_tunnel($self, $self->{tunnel}); };
777 if (my $err = $@) {
778 $self->log('err', $err);
779 $self->{errors} = 1;
780 }
781 }
782 }
783
784 sub phase2_cleanup {
785 my ($self, $vmid, $err) = @_;
786
787 return if !$self->{errors};
788 $self->{phase2errors} = 1;
789
790 $self->log('info', "aborting phase 2 - cleanup resources");
791
792 $self->log('info', "migrate_cancel");
793 eval {
794 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate_cancel");
795 };
796 $self->log('info', "migrate_cancel error: $@") if $@;
797
798 my $conf = $self->{vmconf};
799 delete $conf->{lock};
800 eval { PVE::QemuConfig->write_config($vmid, $conf) };
801 if (my $err = $@) {
802 $self->log('err', $err);
803 }
804
805 # cleanup ressources on target host
806 if ($self->{storage_migration}) {
807
808 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
809 if (my $err = $@) {
810 $self->log('err', $err);
811 }
812
813 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
814 if (my $err = $@) {
815 $self->log('err', $err);
816 }
817 }
818
819 my $nodename = PVE::INotify::nodename();
820
821 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
822 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
823 if (my $err = $@) {
824 $self->log('err', $err);
825 $self->{errors} = 1;
826 }
827
828 if ($self->{tunnel}) {
829 eval { finish_tunnel($self, $self->{tunnel}); };
830 if (my $err = $@) {
831 $self->log('err', $err);
832 $self->{errors} = 1;
833 }
834 }
835 }
836
837 sub phase3 {
838 my ($self, $vmid) = @_;
839
840 my $volids = $self->{volumes};
841 return if $self->{phase2errors};
842
843 # destroy local copies
844 foreach my $volid (@$volids) {
845 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
846 if (my $err = $@) {
847 $self->log('err', "removing local copy of '$volid' failed - $err");
848 $self->{errors} = 1;
849 last if $err =~ /^interrupted by signal$/;
850 }
851 }
852 }
853
854 sub phase3_cleanup {
855 my ($self, $vmid, $err) = @_;
856
857 my $conf = $self->{vmconf};
858 return if $self->{phase2errors};
859
860 if ($self->{storage_migration}) {
861 # finish block-job
862 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}); };
863
864 if (my $err = $@) {
865 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
866 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
867 die "Failed to completed storage migration\n";
868 } else {
869 foreach my $target_drive (keys %{$self->{target_drive}}) {
870 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{volid});
871 $conf->{$target_drive} = PVE::QemuServer::print_drive($vmid, $drive);
872 PVE::QemuConfig->write_config($vmid, $conf);
873 }
874 }
875 }
876
877 # transfer replication state before move config
878 $self->transfer_replication_state();
879
880 # move config to remote node
881 my $conffile = PVE::QemuConfig->config_file($vmid);
882 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
883
884 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
885 if !rename($conffile, $newconffile);
886
887 $self->switch_replication_job_target();
888
889 if ($self->{livemigration}) {
890 if ($self->{storage_migration}) {
891 # remove drives referencing the nbd server from source
892 # otherwise vm_stop might hang later on
893 foreach my $drive (keys %{$self->{target_drive}}){
894 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "device_del", id => $drive);
895 }
896 # stop nbd server on remote vm - requirement for resume since 2.9
897 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
898
899 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
900 if (my $err = $@) {
901 $self->log('err', $err);
902 $self->{errors} = 1;
903 }
904 }
905 # config moved and nbd server stopped - now we can resume vm on target
906 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
907 eval{ PVE::Tools::run_command($cmd, outfunc => sub {},
908 errfunc => sub {
909 my $line = shift;
910 $self->log('err', $line);
911 });
912 };
913 if (my $err = $@) {
914 $self->log('err', $err);
915 $self->{errors} = 1;
916 }
917 }
918
919 eval {
920 my $timer = 0;
921 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
922 $self->log('info', "Waiting for spice server migration");
923 while (1) {
924 my $res = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, 'query-spice');
925 last if int($res->{'migrated'}) == 1;
926 last if $timer > 50;
927 $timer ++;
928 usleep(200000);
929 }
930 }
931 };
932
933 # always stop local VM
934 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
935 if (my $err = $@) {
936 $self->log('err', "stopping vm failed - $err");
937 $self->{errors} = 1;
938 }
939
940 # always deactivate volumes - avoid lvm LVs to be active on several nodes
941 eval {
942 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
943 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
944 };
945 if (my $err = $@) {
946 $self->log('err', $err);
947 $self->{errors} = 1;
948 }
949
950 if($self->{storage_migration}) {
951 # destroy local copies
952 my $volids = $self->{online_local_volumes};
953
954 foreach my $volid (@$volids) {
955 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
956 if (my $err = $@) {
957 $self->log('err', "removing local copy of '$volid' failed - $err");
958 $self->{errors} = 1;
959 last if $err =~ /^interrupted by signal$/;
960 }
961 }
962
963 }
964
965 # clear migrate lock
966 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
967 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
968 }
969
970 sub final_cleanup {
971 my ($self, $vmid) = @_;
972
973 # nothing to do
974 }
975
976 1;