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