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