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