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