]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
remove $vmid param from print_drive
[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 $self->log('info', "copying local disk images") if scalar(%$local_volumes);
451
452 foreach my $volid (keys %$local_volumes) {
453 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
454 my $targetsid = $override_targetsid // $sid;
455 my $ref = $local_volumes->{$volid}->{ref};
456 if ($self->{running} && $ref eq 'config') {
457 push @{$self->{online_local_volumes}}, $volid;
458 } elsif ($ref eq 'generated') {
459 die "can't live migrate VM with local cloudinit disk. use a shared storage instead\n" if $self->{running};
460 # skip all generated volumes but queue them for deletion in phase3_cleanup
461 push @{$self->{volumes}}, $volid;
462 next;
463 } else {
464 next if $self->{replicated_volumes}->{$volid};
465 push @{$self->{volumes}}, $volid;
466 my $opts = $self->{opts};
467 my $insecure = $opts->{migration_type} eq 'insecure';
468 my $with_snapshots = $local_volumes->{$volid}->{snapshots};
469 # use 'migrate' limit for transfer to other node
470 my $bwlimit = PVE::Storage::get_bandwidth_limit('migrate', [$targetsid, $sid], $opts->{bwlimit});
471 # JSONSchema and get_bandwidth_limit use kbps - storage_migrate bps
472 $bwlimit = $bwlimit * 1024 if defined($bwlimit);
473
474 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{ssh_info}, $targetsid,
475 undef, undef, undef, $bwlimit, $insecure, $with_snapshots);
476 }
477 }
478 };
479 die "Failed to sync data - $@" if $@;
480 }
481
482 sub cleanup_remotedisks {
483 my ($self) = @_;
484
485 foreach my $target_drive (keys %{$self->{target_drive}}) {
486
487 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{volid});
488 my ($storeid, $volname) = PVE::Storage::parse_volume_id($drive->{file});
489
490 my $cmd = [@{$self->{rem_ssh}}, 'pvesm', 'free', "$storeid:$volname"];
491
492 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
493 if (my $err = $@) {
494 $self->log('err', $err);
495 $self->{errors} = 1;
496 }
497 }
498 }
499
500 sub phase1 {
501 my ($self, $vmid) = @_;
502
503 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
504
505 my $conf = $self->{vmconf};
506
507 # set migrate lock in config file
508 $conf->{lock} = 'migrate';
509 PVE::QemuConfig->write_config($vmid, $conf);
510
511 sync_disks($self, $vmid);
512
513 };
514
515 sub phase1_cleanup {
516 my ($self, $vmid, $err) = @_;
517
518 $self->log('info', "aborting phase 1 - cleanup resources");
519
520 my $conf = $self->{vmconf};
521 delete $conf->{lock};
522 eval { PVE::QemuConfig->write_config($vmid, $conf) };
523 if (my $err = $@) {
524 $self->log('err', $err);
525 }
526
527 if ($self->{volumes}) {
528 foreach my $volid (@{$self->{volumes}}) {
529 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
530 # fixme: try to remove ?
531 }
532 }
533 }
534
535 sub phase2 {
536 my ($self, $vmid) = @_;
537
538 my $conf = $self->{vmconf};
539
540 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
541
542 my $raddr;
543 my $rport;
544 my $ruri; # the whole migration dst. URI (protocol:address[:port])
545 my $nodename = PVE::INotify::nodename();
546
547 ## start on remote node
548 my $cmd = [@{$self->{rem_ssh}}];
549
550 my $spice_ticket;
551 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
552 my $res = mon_cmd($vmid, 'query-spice');
553 $spice_ticket = $res->{ticket};
554 }
555
556 push @$cmd , 'qm', 'start', $vmid, '--skiplock', '--migratedfrom', $nodename;
557
558 my $migration_type = $self->{opts}->{migration_type};
559
560 push @$cmd, '--migration_type', $migration_type;
561
562 push @$cmd, '--migration_network', $self->{opts}->{migration_network}
563 if $self->{opts}->{migration_network};
564
565 if ($migration_type eq 'insecure') {
566 push @$cmd, '--stateuri', 'tcp';
567 } else {
568 push @$cmd, '--stateuri', 'unix';
569 }
570
571 if ($self->{forcemachine}) {
572 push @$cmd, '--machine', $self->{forcemachine};
573 }
574
575 if ($self->{online_local_volumes}) {
576 push @$cmd, '--targetstorage', ($self->{opts}->{targetstorage} // '1');
577 }
578
579 my $spice_port;
580
581 # Note: We try to keep $spice_ticket secret (do not pass via command line parameter)
582 # instead we pipe it through STDIN
583 PVE::Tools::run_command($cmd, input => $spice_ticket, outfunc => sub {
584 my $line = shift;
585
586 if ($line =~ m/^migration listens on tcp:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+)$/) {
587 $raddr = $1;
588 $rport = int($2);
589 $ruri = "tcp:$raddr:$rport";
590 }
591 elsif ($line =~ m!^migration listens on unix:(/run/qemu-server/(\d+)\.migrate)$!) {
592 $raddr = $1;
593 die "Destination UNIX sockets VMID does not match source VMID" if $vmid ne $2;
594 $ruri = "unix:$raddr";
595 }
596 elsif ($line =~ m/^migration listens on port (\d+)$/) {
597 $raddr = "localhost";
598 $rport = int($1);
599 $ruri = "tcp:$raddr:$rport";
600 }
601 elsif ($line =~ m/^spice listens on port (\d+)$/) {
602 $spice_port = int($1);
603 }
604 elsif ($line =~ m/^storage migration listens on nbd:(localhost|[\d\.]+|\[[\d\.:a-fA-F]+\]):(\d+):exportname=(\S+) volume:(\S+)$/) {
605 my $volid = $4;
606 my $nbd_uri = "nbd:$1:$2:exportname=$3";
607 my $targetdrive = $3;
608 $targetdrive =~ s/drive-//g;
609
610 $self->{target_drive}->{$targetdrive}->{volid} = $volid;
611 $self->{target_drive}->{$targetdrive}->{nbd_uri} = $nbd_uri;
612
613 }
614 }, errfunc => sub {
615 my $line = shift;
616 $self->log('info', $line);
617 });
618
619 die "unable to detect remote migration address\n" if !$raddr;
620
621 $self->log('info', "start remote tunnel");
622
623 if ($migration_type eq 'secure') {
624
625 if ($ruri =~ /^unix:/) {
626 unlink $raddr;
627 $self->{tunnel} = $self->fork_tunnel("$raddr:$raddr");
628 $self->{tunnel}->{sock_addr} = $raddr;
629
630 my $unix_socket_try = 0; # wait for the socket to become ready
631 while (! -S $raddr) {
632 $unix_socket_try++;
633 if ($unix_socket_try > 100) {
634 $self->{errors} = 1;
635 $self->finish_tunnel($self->{tunnel});
636 die "Timeout, migration socket $ruri did not get ready";
637 }
638
639 usleep(50000);
640 }
641
642 } elsif ($ruri =~ /^tcp:/) {
643 my $tunnel_addr;
644 if ($raddr eq "localhost") {
645 # for backwards compatibility with older qemu-server versions
646 my $pfamily = PVE::Tools::get_host_address_family($nodename);
647 my $lport = PVE::Tools::next_migrate_port($pfamily);
648 $tunnel_addr = "$lport:localhost:$rport";
649 }
650
651 $self->{tunnel} = $self->fork_tunnel($tunnel_addr);
652
653 } else {
654 die "unsupported protocol in migration URI: $ruri\n";
655 }
656 } else {
657 #fork tunnel for insecure migration, to send faster commands like resume
658 $self->{tunnel} = $self->fork_tunnel();
659 }
660
661 my $start = time();
662
663 my $opt_bwlimit = $self->{opts}->{bwlimit};
664
665 if (defined($self->{online_local_volumes})) {
666 $self->{storage_migration} = 1;
667 $self->{storage_migration_jobs} = {};
668 $self->log('info', "starting storage migration");
669
670 die "The number of local disks does not match between the source and the destination.\n"
671 if (scalar(keys %{$self->{target_drive}}) != scalar @{$self->{online_local_volumes}});
672 foreach my $drive (keys %{$self->{target_drive}}){
673 my $target = $self->{target_drive}->{$drive};
674 my $nbd_uri = $target->{nbd_uri};
675 my $source_sid = PVE::Storage::Plugin::parse_volume_id($conf->{$drive});
676 my $target_sid = PVE::Storage::Plugin::parse_volume_id($target->{volid});
677 my $bwlimit = PVE::Storage::get_bandwidth_limit('migrate', [$source_sid, $target_sid], $opt_bwlimit);
678
679 $self->log('info', "$drive: start migration to $nbd_uri");
680 PVE::QemuServer::qemu_drive_mirror($vmid, $drive, $nbd_uri, $vmid, undef, $self->{storage_migration_jobs}, 1, undef, $bwlimit);
681 }
682 }
683
684 $self->log('info', "starting online/live migration on $ruri");
685 $self->{livemigration} = 1;
686
687 # load_defaults
688 my $defaults = PVE::QemuServer::load_defaults();
689
690 # migrate speed can be set via bwlimit (datacenter.cfg and API) and via the
691 # migrate_speed parameter in qm.conf - take the lower of the two.
692 my $bwlimit = PVE::Storage::get_bandwidth_limit('migrate', undef, $opt_bwlimit) // 0;
693 my $migrate_speed = $conf->{migrate_speed} // $bwlimit;
694 # migrate_speed is in MB/s, bwlimit in KB/s
695 $migrate_speed *= 1024;
696
697 $migrate_speed = ($bwlimit < $migrate_speed) ? $bwlimit : $migrate_speed;
698
699 # always set migrate speed (overwrite kvm default of 32m) we set a very high
700 # default of 8192m which is basically unlimited
701 $migrate_speed ||= ($defaults->{migrate_speed} || 8192) * 1024;
702
703 # qmp takes migrate_speed in B/s.
704 $migrate_speed *= 1024;
705 $self->log('info', "migrate_set_speed: $migrate_speed");
706 eval {
707 mon_cmd($vmid, "migrate_set_speed", value => int($migrate_speed));
708 };
709 $self->log('info', "migrate_set_speed error: $@") if $@;
710
711 my $migrate_downtime = $defaults->{migrate_downtime};
712 $migrate_downtime = $conf->{migrate_downtime} if defined($conf->{migrate_downtime});
713 if (defined($migrate_downtime)) {
714 $self->log('info', "migrate_set_downtime: $migrate_downtime");
715 eval {
716 mon_cmd($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
717 };
718 $self->log('info', "migrate_set_downtime error: $@") if $@;
719 }
720
721 $self->log('info', "set migration_caps");
722 eval {
723 PVE::QemuServer::set_migration_caps($vmid);
724 };
725 warn $@ if $@;
726
727 # set cachesize to 10% of the total memory
728 my $memory = $conf->{memory} || $defaults->{memory};
729 my $cachesize = int($memory * 1048576 / 10);
730 $cachesize = round_powerof2($cachesize);
731
732 $self->log('info', "set cachesize: $cachesize");
733 eval {
734 mon_cmd($vmid, "migrate-set-cache-size", value => int($cachesize));
735 };
736 $self->log('info', "migrate-set-cache-size error: $@") if $@;
737
738 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga})) {
739 my $rpcenv = PVE::RPCEnvironment::get();
740 my $authuser = $rpcenv->get_user();
741
742 my (undef, $proxyticket) = PVE::AccessControl::assemble_spice_ticket($authuser, $vmid, $self->{node});
743
744 my $filename = "/etc/pve/nodes/$self->{node}/pve-ssl.pem";
745 my $subject = PVE::AccessControl::read_x509_subject_spice($filename);
746
747 $self->log('info', "spice client_migrate_info");
748
749 eval {
750 mon_cmd($vmid, "client_migrate_info", protocol => 'spice',
751 hostname => $proxyticket, 'port' => 0, 'tls-port' => $spice_port,
752 'cert-subject' => $subject);
753 };
754 $self->log('info', "client_migrate_info error: $@") if $@;
755
756 }
757
758 $self->log('info', "start migrate command to $ruri");
759 eval {
760 mon_cmd($vmid, "migrate", uri => $ruri);
761 };
762 my $merr = $@;
763 $self->log('info', "migrate uri => $ruri failed: $merr") if $merr;
764
765 my $lstat = 0;
766 my $usleep = 1000000;
767 my $i = 0;
768 my $err_count = 0;
769 my $lastrem = undef;
770 my $downtimecounter = 0;
771 while (1) {
772 $i++;
773 my $avglstat = $lstat/$i if $lstat;
774
775 usleep($usleep);
776 my $stat;
777 eval {
778 $stat = mon_cmd($vmid, "query-migrate");
779 };
780 if (my $err = $@) {
781 $err_count++;
782 warn "query migrate failed: $err\n";
783 $self->log('info', "query migrate failed: $err");
784 if ($err_count <= 5) {
785 usleep(1000000);
786 next;
787 }
788 die "too many query migrate failures - aborting\n";
789 }
790
791 if (defined($stat->{status}) && $stat->{status} =~ m/^(setup)$/im) {
792 sleep(1);
793 next;
794 }
795
796 if (defined($stat->{status}) && $stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
797 $merr = undef;
798 $err_count = 0;
799 if ($stat->{status} eq 'completed') {
800 my $delay = time() - $start;
801 if ($delay > 0) {
802 my $mbps = sprintf "%.2f", $memory / $delay;
803 my $downtime = $stat->{downtime} || 0;
804 $self->log('info', "migration speed: $mbps MB/s - downtime $downtime ms");
805 }
806 }
807
808 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
809 $self->log('info', "migration status error: $stat->{status}");
810 die "aborting\n"
811 }
812
813 if ($stat->{status} ne 'active') {
814 $self->log('info', "migration status: $stat->{status}");
815 last;
816 }
817
818 if ($stat->{ram}->{transferred} ne $lstat) {
819 my $trans = $stat->{ram}->{transferred} || 0;
820 my $rem = $stat->{ram}->{remaining} || 0;
821 my $total = $stat->{ram}->{total} || 0;
822 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
823 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
824 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
825 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
826 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
827 # reduce sleep if remainig memory is lower than the average transfer speed
828 $usleep = 100000 if $avglstat && $rem < $avglstat;
829
830 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
831 "remaining ${rem}), total ${total})");
832
833 if (${xbzrlecachesize}) {
834 $self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
835 }
836
837 if (($lastrem && $rem > $lastrem ) || ($rem == 0)) {
838 $downtimecounter++;
839 }
840 $lastrem = $rem;
841
842 if ($downtimecounter > 5) {
843 $downtimecounter = 0;
844 $migrate_downtime *= 2;
845 $self->log('info', "migrate_set_downtime: $migrate_downtime");
846 eval {
847 mon_cmd($vmid, "migrate_set_downtime", value => int($migrate_downtime*100)/100);
848 };
849 $self->log('info', "migrate_set_downtime error: $@") if $@;
850 }
851
852 }
853
854
855 $lstat = $stat->{ram}->{transferred};
856
857 } else {
858 die $merr if $merr;
859 die "unable to parse migration status '$stat->{status}' - aborting\n";
860 }
861 }
862 }
863
864 sub phase2_cleanup {
865 my ($self, $vmid, $err) = @_;
866
867 return if !$self->{errors};
868 $self->{phase2errors} = 1;
869
870 $self->log('info', "aborting phase 2 - cleanup resources");
871
872 $self->log('info', "migrate_cancel");
873 eval {
874 mon_cmd($vmid, "migrate_cancel");
875 };
876 $self->log('info', "migrate_cancel error: $@") if $@;
877
878 my $conf = $self->{vmconf};
879 delete $conf->{lock};
880 eval { PVE::QemuConfig->write_config($vmid, $conf) };
881 if (my $err = $@) {
882 $self->log('err', $err);
883 }
884
885 # cleanup ressources on target host
886 if ($self->{storage_migration}) {
887
888 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
889 if (my $err = $@) {
890 $self->log('err', $err);
891 }
892
893 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
894 if (my $err = $@) {
895 $self->log('err', $err);
896 }
897 }
898
899 my $nodename = PVE::INotify::nodename();
900
901 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
902 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
903 if (my $err = $@) {
904 $self->log('err', $err);
905 $self->{errors} = 1;
906 }
907
908 if ($self->{tunnel}) {
909 eval { finish_tunnel($self, $self->{tunnel}); };
910 if (my $err = $@) {
911 $self->log('err', $err);
912 $self->{errors} = 1;
913 }
914 }
915 }
916
917 sub phase3 {
918 my ($self, $vmid) = @_;
919
920 my $volids = $self->{volumes};
921 return if $self->{phase2errors};
922
923 # destroy local copies
924 foreach my $volid (@$volids) {
925 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
926 if (my $err = $@) {
927 $self->log('err', "removing local copy of '$volid' failed - $err");
928 $self->{errors} = 1;
929 last if $err =~ /^interrupted by signal$/;
930 }
931 }
932 }
933
934 sub phase3_cleanup {
935 my ($self, $vmid, $err) = @_;
936
937 my $conf = $self->{vmconf};
938 return if $self->{phase2errors};
939
940 my $tunnel = $self->{tunnel};
941
942 if ($self->{storage_migration}) {
943 # finish block-job
944 eval { PVE::QemuServer::qemu_drive_mirror_monitor($vmid, undef, $self->{storage_migration_jobs}); };
945
946 if (my $err = $@) {
947 eval { PVE::QemuServer::qemu_blockjobs_cancel($vmid, $self->{storage_migration_jobs}) };
948 eval { PVE::QemuMigrate::cleanup_remotedisks($self) };
949 die "Failed to complete storage migration: $err\n";
950 } else {
951 foreach my $target_drive (keys %{$self->{target_drive}}) {
952 my $drive = PVE::QemuServer::parse_drive($target_drive, $self->{target_drive}->{$target_drive}->{volid});
953 $conf->{$target_drive} = PVE::QemuServer::print_drive($drive);
954 PVE::QemuConfig->write_config($vmid, $conf);
955 }
956 }
957 }
958
959 # transfer replication state before move config
960 $self->transfer_replication_state() if $self->{replicated_volumes};
961
962 # move config to remote node
963 my $conffile = PVE::QemuConfig->config_file($vmid);
964 my $newconffile = PVE::QemuConfig->config_file($vmid, $self->{node});
965
966 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
967 if !rename($conffile, $newconffile);
968
969 $self->switch_replication_job_target() if $self->{replicated_volumes};
970
971 if ($self->{livemigration}) {
972 if ($self->{storage_migration}) {
973 # stop nbd server on remote vm - requirement for resume since 2.9
974 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'nbdstop', $vmid];
975
976 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
977 if (my $err = $@) {
978 $self->log('err', $err);
979 $self->{errors} = 1;
980 }
981 }
982
983 # config moved and nbd server stopped - now we can resume vm on target
984 if ($tunnel && $tunnel->{version} && $tunnel->{version} >= 1) {
985 eval {
986 $self->write_tunnel($tunnel, 30, "resume $vmid");
987 };
988 if (my $err = $@) {
989 $self->log('err', $err);
990 $self->{errors} = 1;
991 }
992 } else {
993 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock', '--nocheck'];
994 my $logf = sub {
995 my $line = shift;
996 $self->log('err', $line);
997 };
998 eval { PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => $logf); };
999 if (my $err = $@) {
1000 $self->log('err', $err);
1001 $self->{errors} = 1;
1002 }
1003 }
1004
1005 if ($self->{storage_migration} && PVE::QemuServer::parse_guest_agent($conf)->{fstrim_cloned_disks} && $self->{running}) {
1006 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'guest', 'cmd', $vmid, 'fstrim'];
1007 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
1008 }
1009 }
1010
1011 # close tunnel on successful migration, on error phase2_cleanup closed it
1012 if ($tunnel) {
1013 eval { finish_tunnel($self, $tunnel); };
1014 if (my $err = $@) {
1015 $self->log('err', $err);
1016 $self->{errors} = 1;
1017 }
1018 }
1019
1020 eval {
1021 my $timer = 0;
1022 if (PVE::QemuServer::vga_conf_has_spice($conf->{vga}) && $self->{running}) {
1023 $self->log('info', "Waiting for spice server migration");
1024 while (1) {
1025 my $res = mon_cmd($vmid, 'query-spice');
1026 last if int($res->{'migrated'}) == 1;
1027 last if $timer > 50;
1028 $timer ++;
1029 usleep(200000);
1030 }
1031 }
1032 };
1033
1034 # always stop local VM
1035 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
1036 if (my $err = $@) {
1037 $self->log('err', "stopping vm failed - $err");
1038 $self->{errors} = 1;
1039 }
1040
1041 # always deactivate volumes - avoid lvm LVs to be active on several nodes
1042 eval {
1043 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
1044 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
1045 };
1046 if (my $err = $@) {
1047 $self->log('err', $err);
1048 $self->{errors} = 1;
1049 }
1050
1051 if($self->{storage_migration}) {
1052 # destroy local copies
1053 my $volids = $self->{online_local_volumes};
1054
1055 foreach my $volid (@$volids) {
1056 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
1057 if (my $err = $@) {
1058 $self->log('err', "removing local copy of '$volid' failed - $err");
1059 $self->{errors} = 1;
1060 last if $err =~ /^interrupted by signal$/;
1061 }
1062 }
1063
1064 }
1065
1066 # clear migrate lock
1067 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
1068 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
1069 }
1070
1071 sub final_cleanup {
1072 my ($self, $vmid) = @_;
1073
1074 # nothing to do
1075 }
1076
1077 sub round_powerof2 {
1078 return 1 if $_[0] < 2;
1079 return 2 << int(log($_[0]-1)/log(2));
1080 }
1081
1082 1;