]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
035345889306c0a72c068f8c4d467f5e5d7906cb
[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 $sharedvm = 1;
286
287 my $log_error = sub {
288 my ($msg, $volid) = @_;
289
290 if (defined($volid)) {
291 $local_volumes_errors->{$volid} = $msg;
292 } else {
293 push @$other_errors, $msg;
294 }
295 $abort = 1;
296 };
297
298 my @sids = PVE::Storage::storage_ids($self->{storecfg});
299 foreach my $storeid (@sids) {
300 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
301 next if $scfg->{shared};
302 next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
303
304 # get list from PVE::Storage (for unused volumes)
305 my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
306
307 next if @{$dl->{$storeid}} == 0;
308
309 my $targetsid = $override_targetsid // $storeid;
310
311 # check if storage is available on target node
312 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
313 $sharedvm = 0; # there is a non-shared disk
314
315 PVE::Storage::foreach_volid($dl, sub {
316 my ($volid, $sid, $volname) = @_;
317
318 $local_volumes->{$volid}->{ref} = 'storage';
319 });
320 }
321
322 my $test_volid = sub {
323 my ($volid, $attr) = @_;
324
325 if ($volid =~ m|^/|) {
326 return if $attr->{shared};
327 $local_volumes->{$volid}->{ref} = 'config';
328 die "local file/device\n";
329 }
330
331 my $snaprefs = $attr->{referenced_in_snapshot};
332
333 if ($attr->{cdrom}) {
334 if ($volid eq 'cdrom') {
335 my $msg = "can't migrate local cdrom drive";
336 if (defined($snaprefs) && !$attr->{referenced_in_config}) {
337 my $snapnames = join(', ', sort keys %$snaprefs);
338 $msg .= " (referenced in snapshot - $snapnames)";
339 }
340 &$log_error("$msg\n");
341 return;
342 }
343 return if $volid eq 'none';
344 }
345
346 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
347
348 my $targetsid = $override_targetsid // $sid;
349 # check if storage is available on both nodes
350 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
351 PVE::Storage::storage_check_node($self->{storecfg}, $targetsid, $self->{node});
352
353 return if $scfg->{shared};
354
355 $sharedvm = 0;
356
357 $local_volumes->{$volid}->{ref} = $attr->{referenced_in_config} ? 'config' : 'snapshot';
358
359 if ($attr->{cdrom}) {
360 if ($volid =~ /vm-\d+-cloudinit/) {
361 $local_volumes->{$volid}->{ref} = 'generated';
362 return;
363 }
364 die "local cdrom image\n";
365 }
366
367 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
368
369 die "owned by other VM (owner = VM $owner)\n"
370 if !$owner || ($owner != $self->{vmid});
371
372 my $format = PVE::QemuServer::qemu_img_format($scfg, $volname);
373 $local_volumes->{$volid}->{snapshots} = defined($snaprefs) || ($format =~ /^(?:qcow2|vmdk)$/);
374 if (defined($snaprefs)) {
375 # we cannot migrate shapshots on local storage
376 # exceptions: 'zfspool' or 'qcow2' files (on directory storage)
377
378 die "online storage migration not possible if snapshot exists\n" if $self->{running};
379 if (!($scfg->{type} eq 'zfspool' || $format eq 'qcow2')) {
380 die "non-migratable snapshot exists\n";
381 }
382 }
383
384 die "referenced by linked clone(s)\n"
385 if PVE::Storage::volume_is_base_and_used($self->{storecfg}, $volid);
386 };
387
388 PVE::QemuServer::foreach_volid($conf, sub {
389 my ($volid, $attr) = @_;
390 eval { $test_volid->($volid, $attr); };
391 if (my $err = $@) {
392 &$log_error($err, $volid);
393 }
394 });
395
396 foreach my $vol (sort keys %$local_volumes) {
397 my $ref = $local_volumes->{$vol}->{ref};
398 if ($ref eq 'storage') {
399 $self->log('info', "found local disk '$vol' (via storage)\n");
400 } elsif ($ref eq 'config') {
401 &$log_error("can't live migrate attached local disks without with-local-disks option\n", $vol)
402 if $self->{running} && !$self->{opts}->{"with-local-disks"};
403 $self->log('info', "found local disk '$vol' (in current VM config)\n");
404 } elsif ($ref eq 'snapshot') {
405 $self->log('info', "found local disk '$vol' (referenced by snapshot(s))\n");
406 } elsif ($ref eq 'generated') {
407 $self->log('info', "found generated disk '$vol' (in current VM config)\n");
408 } else {
409 $self->log('info', "found local disk '$vol'\n");
410 }
411 }
412
413 foreach my $vol (sort keys %$local_volumes_errors) {
414 $self->log('warn', "can't migrate local disk '$vol': $local_volumes_errors->{$vol}");
415 }
416 foreach my $err (@$other_errors) {
417 $self->log('warn', "$err");
418 }
419
420 if ($abort) {
421 die "can't migrate VM - check log\n";
422 }
423
424 # additional checks for local storage
425 foreach my $volid (keys %$local_volumes) {
426 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
427 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $sid);
428
429 my $migratable = $scfg->{type} =~ /^(?:dir|zfspool|lvmthin|lvm)$/;
430
431 die "can't migrate '$volid' - storage type '$scfg->{type}' not supported\n"
432 if !$migratable;
433
434 # image is a linked clone on local storage, se we can't migrate.
435 if (my $basename = (PVE::Storage::parse_volname($self->{storecfg}, $volid))[3]) {
436 die "can't migrate '$volid' as it's a clone of '$basename'";
437 }
438 }
439
440 my $rep_cfg = PVE::ReplicationConfig->new();
441 if (my $jobcfg = $rep_cfg->find_local_replication_job($vmid, $self->{node})) {
442 die "can't live migrate VM with replicated volumes\n" if $self->{running};
443 $self->log('info', "replicating disk images");
444 my $start_time = time();
445 my $logfunc = sub { $self->log('info', shift) };
446 $self->{replicated_volumes} = PVE::Replication::run_replication(
447 'PVE::QemuConfig', $jobcfg, $start_time, $start_time, $logfunc);
448 }
449
450 # sizes in config have to be accurate for remote node to correctly
451 # allocate disks, rescan to be sure
452 my $volid_hash = PVE::QemuServer::scan_volids($self->{storecfg}, $vmid);
453 PVE::QemuServer::foreach_drive($conf, sub {
454 my ($key, $drive) = @_;
455 my ($updated, $old_size, $new_size) = PVE::QemuServer::update_disksize($drive, $volid_hash);
456 if (defined($updated)) {
457 $conf->{$key} = PVE::QemuServer::print_drive($updated);
458 $self->log('info', "size of disk '$updated->{file}' ($key) updated from $old_size to $new_size\n");
459 }
460 });
461
462 $self->log('info', "copying local disk images") if scalar(%$local_volumes);
463
464 foreach my $volid (keys %$local_volumes) {
465 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
466 my $targetsid = $override_targetsid // $sid;
467 my $ref = $local_volumes->{$volid}->{ref};
468 if ($self->{running} && $ref eq 'config') {
469 push @{$self->{online_local_volumes}}, $volid;
470 } elsif ($ref eq 'generated') {
471 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n" if $self->{running};
472 # skip all generated volumes but queue them for deletion in phase3_cleanup
473 push @{$self->{volumes}}, $volid;
474 next;
475 } else {
476 next if $self->{replicated_volumes}->{$volid};
477 push @{$self->{volumes}}, $volid;
478 my $opts = $self->{opts};
479 my $insecure = $opts->{migration_type} eq 'insecure';
480 my $with_snapshots = $local_volumes->{$volid}->{snapshots};
481 # use 'migrate' limit for transfer to other node
482 my $bwlimit = PVE::Storage::get_bandwidth_limit('migrate', [$targetsid, $sid], $opts->{bwlimit});
483 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
484 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
485
486 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{ssh_info}, $targetsid,
487 undef, undef, undef, $bwlimit, $insecure, $with_snapshots);
488 }
489 }
490 };
491 die "Failed to sync data - $@" if $@;
492 }
493
494 sub cleanup_remotedisks {
495 my ($self) = @_;
496
497 foreach my $target_drive (keys %{$self->{target_drive}}) {
498
499 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{volid});
500 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
501
502 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
503
504 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
505 if (my $err = $@) {
506 $self->log('err', $err);
507 $self->{errors} = 1;
508 }
509 }
510 }
511
512 sub phase1 {
513 my ($self, $vmid) = @_;
514
515 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
516
517 my $conf = $self->{vmconf};
518
519 # set migrate lock in config file
520 $conf->{lock} = 'migrate';
521 PVE::QemuConfig->write_config($vmid, $conf);
522
523 sync_disks($self, $vmid);
524
525 # sync_disks fixes disk sizes to match their actual size, write changes so
526 # target allocates correct volumes
527 PVE::QemuConfig->write_config($vmid, $conf);
528 };
529
530 sub phase1_cleanup {
531 my ($self, $vmid, $err) = @_;
532
533 $self->log('info', "aborting phase 1 - cleanup resources");
534
535 my $conf = $self->{vmconf};
536 delete $conf->{lock};
537 eval { PVE::QemuConfig->write_config($vmid, $conf) };
538 if (my $err = $@) {
539 $self->log('err', $err);
540 }
541
542 if ($self->{volumes}) {
543 foreach my $volid (@{$self->{volumes}}) {
544 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
545 # fixme: try to remove ?
546 }
547 }
548 }
549
550 sub phase2 {
551 my ($self, $vmid) = @_;
552
553 my $conf = $self->{vmconf};
554
555 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
556
557 my $raddr;
558 my $rport;
559 my $ruri; # the whole migration dst. URI (protocol:address[:port])
560 my $nodename = PVE::INotify::nodename();
561
562 ## start on remote node
563 my $cmd = [@{$self->{rem_ssh}}];
564
565 my $spice_ticket;
566 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
567 my $res = mon_cmd($vmid, 'query-spice');
568 $spice_ticket = $res->{ticket};
569 }
570
571 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
572
573 my $migration_type = $self->{opts}->{migration_type};
574
575 push @$cmd, '--migration_type', $migration_type;
576
577 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
578 if $self->{opts}->{migration_network};
579
580 if ($migration_type eq 'insecure') {
581 push @$cmd, '--stateuri', 'tcp';
582 } else {
583 push @$cmd, '--stateuri', 'unix';
584 }
585
586 if ($self->{forcemachine}) {
587 push @$cmd, '--machine', $self->{forcemachine};
588 }
589
590 if ($self->{online_local_volumes}) {
591 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
592 }
593
594 my $spice_port;
595
596 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
597 # instead we pipe it through STDIN
598 my $exitcode = PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
599 my $line = shift;
600
601 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
602 $raddr = $1;
603 $rport = int($2);
604 $ruri = "tcp:$raddr:$rport";
605 }
606 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
607 $raddr = $1;
608 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
609 $ruri = "unix:$raddr";
610 }
611 elsif ($line =~ m/^migration listens on port (\d+)$/) {
612 $raddr = "localhost";
613 $rport = int($1);
614 $ruri = "tcp:$raddr:$rport";
615 }
616 elsif ($line =~ m/^spice listens on port (\d+)$/) {
617 $spice_port = int($1);
618 }
619 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
620 my $volid = $4;
621 my $nbd_uri = "nbd:$1:$2:exportname=$3";
622 my $targetdrive = $3;
623 $targetdrive =~ s/drive-//g;
624
625 $self->{target_drive}->{$targetdrive}->{volid} = $volid;
626 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
627
628 } elsif ($line =~ m/^QEMU: (.*)$/) {
629 $self->log('info', "[$self->{node}] $1\n");
630 }
631 }, errfunc => sub {
632 my $line = shift;
633 $self->log('info', "[$self->{node}] $line");
634 }, noerr => 1);
635
636 die "remote command failed with exit code $exitcode\n" if $exitcode;
637
638 die "unable to detect remote migration address\n" if !$raddr;
639
640 $self->log('info', "start remote tunnel");
641
642 if ($migration_type eq 'secure') {
643
644 if ($ruri =~ /^unix:/) {
645 unlink $raddr;
646 $self->{tunnel} = $self->fork_tunnel("$raddr:$raddr");
647 $self->{tunnel}->{sock_addr} = $raddr;
648
649 my $unix_socket_try = 0; # wait for the socket to become ready
650 while (! -S $raddr) {
651 $unix_socket_try++;
652 if ($unix_socket_try > 100) {
653 $self->{errors} = 1;
654 $self->finish_tunnel($self->{tunnel});
655 die "Timeout, migration socket $ruri did not get ready";
656 }
657
658 usleep(50000);
659 }
660
661 } elsif ($ruri =~ /^tcp:/) {
662 my $tunnel_addr;
663 if ($raddr eq "localhost") {
664 # for backwards compatibility with older qemu-server versions
665 my $pfamily = PVE::Tools::get_host_address_family($nodename);
666 my $lport = PVE::Tools::next_migrate_port($pfamily);
667 $tunnel_addr = "$lport:localhost:$rport";
668 }
669
670 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
671
672 } else {
673 die "unsupported protocol in migration URI: $ruri\n";
674 }
675 } else {
676 #fork tunnel for insecure migration, to send faster commands like resume
677 $self->{tunnel} = $self->fork_tunnel();
678 }
679
680 my $start = time();
681
682 my $opt_bwlimit = $self->{opts}->{bwlimit};
683
684 if (defined($self->{online_local_volumes})) {
685 $self->{storage_migration} = 1;
686 $self->{storage_migration_jobs} = {};
687 $self->log('info', "starting storage migration");
688
689 die "The number of local disks does not match between the source and the destination.\n"
690 if (scalar(keys %{$self->{target_drive}}) != scalar @{$self->{online_local_volumes}});
691 foreach my $drive (keys %{$self->{target_drive}}){
692 my $target = $self->{target_drive}->{$drive};
693 my $nbd_uri = $target->{nbd_uri};
694 my $source_sid = PVE::Storage::Plugin::parse_volume_id($conf->{$drive});
695 my $target_sid = PVE::Storage::Plugin::parse_volume_id($target->{volid});
696 my $bwlimit = PVE::Storage::get_bandwidth_limit('migrate', [$source_sid, $target_sid], $opt_bwlimit);
697
698 $self->log('info', "$drive: start migration to $nbd_uri");
699 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 1, undef, $bwlimit);
700 }
701 }
702
703 $self->log('info', "starting online/live migration on $ruri");
704 $self->{livemigration} = 1;
705
706 # load_defaults
707 my $defaults = PVE::QemuServer::load_defaults();
708
709 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
710 # migrate_speed parameter in qm.conf - take the lower of the two.
711 my $bwlimit = PVE::Storage::get_bandwidth_limit('migrate', undef, $opt_bwlimit) // 0;
712 my $migrate_speed = $conf->{migrate_speed} // $bwlimit;
713 # migrate_speed is in MB/s, bwlimit in KB/s
714 $migrate_speed *= 1024;
715
716 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
717
718 # always set migrate speed (overwrite kvm default of 32m) we set a very high
719 # default of 8192m which is basically unlimited
720 $migrate_speed ||= ($defaults->{migrate_speed} || 8192) * 1024;
721
722 # qmp takes migrate_speed in B/s.
723 $migrate_speed *= 1024;
724 $self->log('info', "migrate_set_speed: $migrate_speed");
725 eval {
726 mon_cmd($vmid, "migrate_set_speed", value => int($migrate_speed));
727 };
728 $self->log('info', "migrate_set_speed error: $@") if $@;
729
730 my $migrate_downtime = $defaults->{migrate_downtime};
731 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
732 if (defined($migrate_downtime)) {
733 $self->log('info', "migrate_set_downtime: $migrate_downtime");
734 eval {
735 mon_cmd($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
736 };
737 $self->log('info', "migrate_set_downtime error: $@") if $@;
738 }
739
740 $self->log('info', "set migration_caps");
741 eval {
742 PVE::QemuServer::set_migration_caps($vmid);
743 };
744 warn $@ if $@;
745
746 # set cachesize to 10% of the total memory
747 my $memory = $conf->{memory} || $defaults->{memory};
748 my $cachesize = int($memory * 1048576 / 10);
749 $cachesize = round_powerof2($cachesize);
750
751 $self->log('info', "set cachesize: $cachesize");
752 eval {
753 mon_cmd($vmid, "migrate-set-cache-size", value => int($cachesize));
754 };
755 $self->log('info', "migrate-set-cache-size error: $@") if $@;
756
757 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
758 my $rpcenv = PVE::RPCEnvironment::get();
759 my $authuser = $rpcenv->get_user();
760
761 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
762
763 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
764 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
765
766 $self->log('info', "spice client_migrate_info");
767
768 eval {
769 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
770 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
771 'cert-subject' => $subject);
772 };
773 $self->log('info', "client_migrate_info error: $@") if $@;
774
775 }
776
777 $self->log('info', "start migrate command to $ruri");
778 eval {
779 mon_cmd($vmid, "migrate", uri => $ruri);
780 };
781 my $merr = $@;
782 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
783
784 my $lstat = 0;
785 my $usleep = 1000000;
786 my $i = 0;
787 my $err_count = 0;
788 my $lastrem = undef;
789 my $downtimecounter = 0;
790 while (1) {
791 $i++;
792 my $avglstat = $lstat/$i if $lstat;
793
794 usleep($usleep);
795 my $stat;
796 eval {
797 $stat = mon_cmd($vmid, "query-migrate");
798 };
799 if (my $err = $@) {
800 $err_count++;
801 warn "query migrate failed: $err\n";
802 $self->log('info', "query migrate failed: $err");
803 if ($err_count <= 5) {
804 usleep(1000000);
805 next;
806 }
807 die "too many query migrate failures - aborting\n";
808 }
809
810 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
811 sleep(1);
812 next;
813 }
814
815 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
816 $merr = undef;
817 $err_count = 0;
818 if ($stat->{status} eq 'completed') {
819 my $delay = time() - $start;
820 if ($delay > 0) {
821 my $mbps = sprintf "%.2f", $memory / $delay;
822 my $downtime = $stat->{downtime} || 0;
823 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
824 }
825 }
826
827 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
828 $self->log('info', "migration status error: $stat->{status}");
829 die "aborting\n"
830 }
831
832 if ($stat->{status} ne 'active') {
833 $self->log('info', "migration status: $stat->{status}");
834 last;
835 }
836
837 if ($stat->{ram}->{transferred} ne $lstat) {
838 my $trans = $stat->{ram}->{transferred} || 0;
839 my $rem = $stat->{ram}->{remaining} || 0;
840 my $total = $stat->{ram}->{total} || 0;
841 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
842 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
843 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
844 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
845 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
846 # reduce sleep if remainig memory is lower than the average transfer speed
847 $usleep = 100000 if $avglstat && $rem < $avglstat;
848
849 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
850 "remaining ${rem}), total ${total})");
851
852 if (${xbzrlecachesize}) {
853 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
854 }
855
856 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
857 $downtimecounter++;
858 }
859 $lastrem = $rem;
860
861 if ($downtimecounter > 5) {
862 $downtimecounter = 0;
863 $migrate_downtime *= 2;
864 $self->log('info', "migrate_set_downtime: $migrate_downtime");
865 eval {
866 mon_cmd($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
867 };
868 $self->log('info', "migrate_set_downtime error: $@") if $@;
869 }
870
871 }
872
873
874 $lstat = $stat->{ram}->{transferred};
875
876 } else {
877 die $merr if $merr;
878 die "unable to parse migration status '$stat->{status}' - aborting\n";
879 }
880 }
881 }
882
883 sub phase2_cleanup {
884 my ($self, $vmid, $err) = @_;
885
886 return if !$self->{errors};
887 $self->{phase2errors} = 1;
888
889 $self->log('info', "aborting phase 2 - cleanup resources");
890
891 $self->log('info', "migrate_cancel");
892 eval {
893 mon_cmd($vmid, "migrate_cancel");
894 };
895 $self->log('info', "migrate_cancel error: $@") if $@;
896
897 my $conf = $self->{vmconf};
898 delete $conf->{lock};
899 eval { PVE::QemuConfig->write_config($vmid, $conf) };
900 if (my $err = $@) {
901 $self->log('err', $err);
902 }
903
904 # cleanup ressources on target host
905 if ($self->{storage_migration}) {
906
907 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
908 if (my $err = $@) {
909 $self->log('err', $err);
910 }
911
912 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
913 if (my $err = $@) {
914 $self->log('err', $err);
915 }
916 }
917
918 my $nodename = PVE::INotify::nodename();
919
920 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
921 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
922 if (my $err = $@) {
923 $self->log('err', $err);
924 $self->{errors} = 1;
925 }
926
927 if ($self->{tunnel}) {
928 eval { finish_tunnel($self, $self->{tunnel}); };
929 if (my $err = $@) {
930 $self->log('err', $err);
931 $self->{errors} = 1;
932 }
933 }
934 }
935
936 sub phase3 {
937 my ($self, $vmid) = @_;
938
939 my $volids = $self->{volumes};
940 return if $self->{phase2errors};
941
942 # destroy local copies
943 foreach my $volid (@$volids) {
944 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
945 if (my $err = $@) {
946 $self->log('err', "removing local copy of '$volid' failed - $err");
947 $self->{errors} = 1;
948 last if $err =~ /^interrupted by signal$/;
949 }
950 }
951 }
952
953 sub phase3_cleanup {
954 my ($self, $vmid, $err) = @_;
955
956 my $conf = $self->{vmconf};
957 return if $self->{phase2errors};
958
959 my $tunnel = $self->{tunnel};
960
961 if ($self->{storage_migration}) {
962 # finish block-job
963 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}); };
964
965 if (my $err = $@) {
966 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
967 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
968 die "Failed to complete storage migration: $err\n";
969 } else {
970 foreach my $target_drive (keys %{$self->{target_drive}}) {
971 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{volid});
972 $conf->{$target_drive} = PVE::QemuServer::print_drive($drive);
973 PVE::QemuConfig->write_config($vmid, $conf);
974 }
975 }
976 }
977
978 # transfer replication state before move config
979 $self->transfer_replication_state() if $self->{replicated_volumes};
980
981 # move config to remote node
982 my $conffile = PVE::QemuConfig->config_file($vmid);
983 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
984
985 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
986 if !rename($conffile, $newconffile);
987
988 $self->switch_replication_job_target() if $self->{replicated_volumes};
989
990 if ($self->{livemigration}) {
991 if ($self->{storage_migration}) {
992 # stop nbd server on remote vm - requirement for resume since 2.9
993 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
994
995 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
996 if (my $err = $@) {
997 $self->log('err', $err);
998 $self->{errors} = 1;
999 }
1000 }
1001
1002 # config moved and nbd server stopped - now we can resume vm on target
1003 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
1004 eval {
1005 $self->write_tunnel($tunnel, 30, "resume $vmid");
1006 };
1007 if (my $err = $@) {
1008 $self->log('err', $err);
1009 $self->{errors} = 1;
1010 }
1011 } else {
1012 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
1013 my $logf = sub {
1014 my $line = shift;
1015 $self->log('err', $line);
1016 };
1017 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
1018 if (my $err = $@) {
1019 $self->log('err', $err);
1020 $self->{errors} = 1;
1021 }
1022 }
1023
1024 if ($self->{storage_migration} && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks} && $self->{running}) {
1025 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1026 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1027 }
1028 }
1029
1030 # close tunnel on successful migration, on error phase2_cleanup closed it
1031 if ($tunnel) {
1032 eval { finish_tunnel($self, $tunnel); };
1033 if (my $err = $@) {
1034 $self->log('err', $err);
1035 $self->{errors} = 1;
1036 }
1037 }
1038
1039 eval {
1040 my $timer = 0;
1041 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1042 $self->log('info', "Waiting for spice server migration");
1043 while (1) {
1044 my $res = mon_cmd($vmid, 'query-spice');
1045 last if int($res->{'migrated'}) == 1;
1046 last if $timer > 50;
1047 $timer ++;
1048 usleep(200000);
1049 }
1050 }
1051 };
1052
1053 # always stop local VM
1054 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1055 if (my $err = $@) {
1056 $self->log('err', "stopping vm failed - $err");
1057 $self->{errors} = 1;
1058 }
1059
1060 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1061 eval {
1062 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
1063 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
1064 };
1065 if (my $err = $@) {
1066 $self->log('err', $err);
1067 $self->{errors} = 1;
1068 }
1069
1070 if($self->{storage_migration}) {
1071 # destroy local copies
1072 my $volids = $self->{online_local_volumes};
1073
1074 foreach my $volid (@$volids) {
1075 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1076 if (my $err = $@) {
1077 $self->log('err', "removing local copy of '$volid' failed - $err");
1078 $self->{errors} = 1;
1079 last if $err =~ /^interrupted by signal$/;
1080 }
1081 }
1082
1083 }
1084
1085 # clear migrate lock
1086 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1087 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1088 }
1089
1090 sub final_cleanup {
1091 my ($self, $vmid) = @_;
1092
1093 # nothing to do
1094 }
1095
1096 sub round_powerof2 {
1097 return 1 if $_[0] < 2;
1098 return 2 << int(log($_[0]-1)/log(2));
1099 }
1100
1101 1;