]> git.proxmox.com Git - qemu-server.git/blob - PVE/QemuMigrate.pm
fix check for non-shared disks
[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 PVE::INotify;
9 use PVE::Cluster;
10 use PVE::Storage;
11 use PVE::QemuServer;
12 use Time::HiRes qw( usleep );
13
14 use base qw(PVE::AbstractMigrate);
15
16 sub fork_command_pipe {
17 my ($self, $cmd) = @_;
18
19 my $reader = IO::File->new();
20 my $writer = IO::File->new();
21
22 my $orig_pid = $$;
23
24 my $cpid;
25
26 eval { $cpid = open2($reader, $writer, @$cmd); };
27
28 my $err = $@;
29
30 # catch exec errors
31 if ($orig_pid != $$) {
32 $self->log('err', "can't fork command pipe\n");
33 POSIX::_exit(1);
34 kill('KILL', $$);
35 }
36
37 die $err if $err;
38
39 return { writer => $writer, reader => $reader, pid => $cpid };
40 }
41
42 sub finish_command_pipe {
43 my ($self, $cmdpipe, $timeout) = @_;
44
45 my $writer = $cmdpipe->{writer};
46 my $reader = $cmdpipe->{reader};
47
48 $writer->close();
49 $reader->close();
50
51 my $cpid = $cmdpipe->{pid};
52
53 if ($timeout) {
54 for (my $i = 0; $i < $timeout; $i++) {
55 return if !PVE::ProcFSTools::check_process_running($cpid);
56 sleep(1);
57 }
58 }
59
60 $self->log('info', "ssh tunnel still running - terminating now with SIGTERM\n");
61 kill(15, $cpid);
62
63 # wait again
64 for (my $i = 0; $i < 10; $i++) {
65 return if !PVE::ProcFSTools::check_process_running($cpid);
66 sleep(1);
67 }
68
69 $self->log('info', "ssh tunnel still running - terminating now with SIGKILL\n");
70 kill 9, $cpid;
71 sleep 1;
72 }
73
74 sub fork_tunnel {
75 my ($self, $nodeip, $lport, $rport) = @_;
76
77 my $cmd = [@{$self->{rem_ssh}}, '-L', "$lport:localhost:$rport",
78 'qm', 'mtunnel' ];
79
80 my $tunnel = $self->fork_command_pipe($cmd);
81
82 my $reader = $tunnel->{reader};
83
84 my $helo;
85 eval {
86 PVE::Tools::run_with_timeout(60, sub { $helo = <$reader>; });
87 die "no reply\n" if !$helo;
88 die "no quorum on target node\n" if $helo =~ m/^no quorum$/;
89 die "got strange reply from mtunnel ('$helo')\n"
90 if $helo !~ m/^tunnel online$/;
91 };
92 my $err = $@;
93
94 if ($err) {
95 $self->finish_command_pipe($tunnel);
96 die "can't open migration tunnel - $err";
97 }
98 return $tunnel;
99 }
100
101 sub finish_tunnel {
102 my ($self, $tunnel) = @_;
103
104 my $writer = $tunnel->{writer};
105
106 eval {
107 PVE::Tools::run_with_timeout(30, sub {
108 print $writer "quit\n";
109 $writer->flush();
110 });
111 };
112 my $err = $@;
113
114 $self->finish_command_pipe($tunnel, 30);
115
116 die $err if $err;
117 }
118
119 sub lock_vm {
120 my ($self, $vmid, $code, @param) = @_;
121
122 return PVE::QemuServer::lock_config($vmid, $code, @param);
123 }
124
125 sub prepare {
126 my ($self, $vmid) = @_;
127
128 my $online = $self->{opts}->{online};
129
130 $self->{storecfg} = PVE::Storage::config();
131
132 # test is VM exist
133 my $conf = $self->{vmconf} = PVE::QemuServer::load_config($vmid);
134
135 PVE::QemuServer::check_lock($conf);
136
137 my $running = 0;
138 if (my $pid = PVE::QemuServer::check_running($vmid)) {
139 die "cant migrate running VM without --online\n" if !$online;
140 $running = $pid;
141 }
142
143 if (my $loc_res = PVE::QemuServer::check_local_resources($conf, 1)) {
144 if ($self->{running} || !$self->{opts}->{force}) {
145 die "can't migrate VM which uses local devices\n";
146 } else {
147 $self->log('info', "migrating VM which uses local devices");
148 }
149 }
150
151 # activate volumes
152 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
153 PVE::Storage::activate_volumes($self->{storecfg}, $vollist);
154
155 # fixme: check if storage is available on both nodes
156
157 # test ssh connection
158 my $cmd = [ @{$self->{rem_ssh}}, '/bin/true' ];
159 eval { $self->cmd_quiet($cmd); };
160 die "Can't connect to destination address using public key\n" if $@;
161
162 return $running;
163 }
164
165 sub sync_disks {
166 my ($self, $vmid) = @_;
167
168 $self->log('info', "copying disk images");
169
170 my $conf = $self->{vmconf};
171
172 $self->{volumes} = [];
173
174 my $res = [];
175
176 eval {
177
178 my $volhash = {};
179 my $cdromhash = {};
180
181 my $sharedvm = 1;
182
183 my @sids = PVE::Storage::storage_ids($self->{storecfg});
184 foreach my $storeid (@sids) {
185 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $storeid);
186 next if $scfg->{shared};
187 next if !PVE::Storage::storage_check_enabled($self->{storecfg}, $storeid, undef, 1);
188
189 # get list from PVE::Storage (for unused volumes)
190 my $dl = PVE::Storage::vdisk_list($self->{storecfg}, $storeid, $vmid);
191 PVE::Storage::foreach_volid($dl, sub {
192 my ($volid, $sid, $volname) = @_;
193
194 # check if storage is available on target node
195 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
196
197 $volhash->{$volid} = 1;
198 $sharedvm = 0; # there is a non-shared disk
199 });
200 }
201
202 # and add used,owned/non-shared disks (just to be sure we have all)
203
204 PVE::QemuServer::foreach_drive($conf, sub {
205 my ($ds, $drive) = @_;
206
207 my $volid = $drive->{file};
208 return if !$volid;
209
210 die "cant migrate local file/device '$volid'\n" if $volid =~ m|^/|;
211
212 if (PVE::QemuServer::drive_is_cdrom($drive)) {
213 die "cant migrate local cdrom drive\n" if $volid eq 'cdrom';
214 return if $volid eq 'none';
215 $cdromhash->{$volid} = 1;
216 }
217
218 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
219
220 # check if storage is available on both nodes
221 my $scfg = PVE::Storage::storage_check_node($self->{storecfg}, $sid);
222 PVE::Storage::storage_check_node($self->{storecfg}, $sid, $self->{node});
223
224 return if $scfg->{shared};
225
226 die "can't migrate local cdrom '$volid'\n" if $cdromhash->{$volid};
227
228 $sharedvm = 0;
229
230 my ($path, $owner) = PVE::Storage::path($self->{storecfg}, $volid);
231
232 die "can't migrate volume '$volid' - owned by other VM (owner = VM $owner)\n"
233 if !$owner || ($owner != $self->{vmid});
234
235 $volhash->{$volid} = 1;
236 });
237
238 if ($self->{running} && !$sharedvm) {
239 die "can't do online migration - VM uses local disks\n";
240 }
241
242 # do some checks first
243 foreach my $volid (keys %$volhash) {
244 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
245 my $scfg = PVE::Storage::storage_config($self->{storecfg}, $sid);
246
247 die "can't migrate '$volid' - storagy type '$scfg->{type}' not supported\n"
248 if $scfg->{type} ne 'dir';
249 }
250
251 foreach my $volid (keys %$volhash) {
252 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid);
253 push @{$self->{volumes}}, $volid;
254 PVE::Storage::storage_migrate($self->{storecfg}, $volid, $self->{nodeip}, $sid);
255 }
256 };
257 die "Failed to sync data - $@" if $@;
258 }
259
260 sub phase1 {
261 my ($self, $vmid) = @_;
262
263 $self->log('info', "starting migration of VM $vmid to node '$self->{node}' ($self->{nodeip})");
264
265 my $conf = $self->{vmconf};
266
267 # set migrate lock in config file
268 $conf->{lock} = 'migrate';
269 PVE::QemuServer::update_config_nolock($vmid, $conf, 1);
270
271 sync_disks($self, $vmid);
272
273 };
274
275 sub phase1_cleanup {
276 my ($self, $vmid, $err) = @_;
277
278 $self->log('info', "aborting phase 1 - cleanup resources");
279
280 my $conf = $self->{vmconf};
281 delete $conf->{lock};
282 eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
283 if (my $err = $@) {
284 $self->log('err', $err);
285 }
286
287 if ($self->{volumes}) {
288 foreach my $volid (@{$self->{volumes}}) {
289 $self->log('err', "found stale volume copy '$volid' on node '$self->{node}'");
290 # fixme: try to remove ?
291 }
292 }
293 }
294
295 sub phase2 {
296 my ($self, $vmid) = @_;
297
298 my $conf = $self->{vmconf};
299
300 $self->log('info', "starting VM $vmid on remote node '$self->{node}'");
301
302 my $rport;
303
304 my $nodename = PVE::INotify::nodename();
305
306 ## start on remote node
307 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'start',
308 $vmid, '--stateuri', 'tcp', '--skiplock', '--migratedfrom', $nodename];
309
310 PVE::Tools::run_command($cmd, outfunc => sub {
311 my $line = shift;
312
313 if ($line =~ m/^migration listens on port (\d+)$/) {
314 $rport = $1;
315 }
316 }, errfunc => sub {});
317
318 die "unable to detect remote migration port\n" if !$rport;
319
320 $self->log('info', "starting migration tunnel");
321
322 ## create tunnel to remote port
323 my $lport = PVE::QemuServer::next_migrate_port();
324 $self->{tunnel} = $self->fork_tunnel($self->{nodeip}, $lport, $rport);
325
326 $self->log('info', "starting online/live migration on port $lport");
327 # start migration
328
329 my $start = time();
330
331 my $capabilities = {};
332 $capabilities->{capability} = "xbzrle";
333 $capabilities->{state} = JSON::false;
334
335 eval {
336 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-capabilities", capabilities => [$capabilities]);
337 };
338
339 #set cachesize 10% of the total memory
340 my $cachesize = int($conf->{memory}*1048576/10);
341 eval {
342 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate-set-cache-size", value => $cachesize);
343 };
344
345 eval {
346 PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "migrate", uri => "tcp:localhost:$lport");
347 };
348 my $merr = $@;
349
350 my $lstat = 0;
351 my $usleep = 2000000;
352 my $i = 0;
353 my $err_count = 0;
354 while (1) {
355 $i++;
356 my $avglstat = $lstat/$i if $lstat;
357
358 usleep($usleep);
359 my $stat;
360 eval {
361 $stat = PVE::QemuServer::vm_mon_cmd_nocheck($vmid, "query-migrate");
362 };
363 if (my $err = $@) {
364 $err_count++;
365 warn "query migrate failed: $err\n";
366 if ($err_count <= 5) {
367 usleep(1000000);
368 next;
369 }
370 die "too many query migrate failures - aborting\n";
371 }
372 if ($stat->{status} =~ m/^(active|completed|failed|cancelled)$/im) {
373 $merr = undef;
374 $err_count = 0;
375 if ($stat->{status} eq 'completed') {
376 my $delay = time() - $start;
377 if ($delay > 0) {
378 my $mbps = sprintf "%.2f", $conf->{memory}/$delay;
379 $self->log('info', "migration speed: $mbps MB/s");
380 }
381 }
382
383 if ($stat->{status} eq 'failed' || $stat->{status} eq 'cancelled') {
384 die "aborting\n"
385 }
386
387 if ($stat->{status} ne 'active') {
388 $self->log('info', "migration status: $stat->{status}");
389 last;
390 }
391
392 if ($stat->{ram}->{transferred} ne $lstat) {
393 my $trans = $stat->{ram}->{transferred} || 0;
394 my $rem = $stat->{ram}->{remaining} || 0;
395 my $total = $stat->{ram}->{total} || 0;
396 my $xbzrlecachesize = $stat->{"xbzrle-cache"}->{"cache-size"} || 0;
397 my $xbzrlebytes = $stat->{"xbzrle-cache"}->{"bytes"} || 0;
398 my $xbzrlepages = $stat->{"xbzrle-cache"}->{"pages"} || 0;
399 my $xbzrlecachemiss = $stat->{"xbzrle-cache"}->{"cache-miss"} || 0;
400 my $xbzrleoverflow = $stat->{"xbzrle-cache"}->{"overflow"} || 0;
401 #reduce sleep if remainig memory if lower than the everage transfert
402 $usleep = 300000 if $avglstat && $rem < $avglstat;
403
404 $self->log('info', "migration status: $stat->{status} (transferred ${trans}, " .
405 "remaining ${rem}), total ${total})");
406
407 #$self->log('info', "migration xbzrle cachesize: ${xbzrlecachesize} transferred ${xbzrlebytes} pages ${xbzrlepages} cachemiss ${xbzrlecachemiss} overflow ${xbzrleoverflow}");
408 }
409
410 $lstat = $stat->{ram}->{transferred};
411
412 } else {
413 die $merr if $merr;
414 die "unable to parse migration status '$stat->{status}' - aborting\n";
415 }
416 }
417 }
418
419 sub phase2_cleanup {
420 my ($self, $vmid, $err) = @_;
421
422 return if !$self->{errors};
423 $self->{phase2errors} = 1;
424
425 $self->log('info', "aborting phase 2 - cleanup resources");
426
427 my $conf = $self->{vmconf};
428 delete $conf->{lock};
429 eval { PVE::QemuServer::update_config_nolock($vmid, $conf, 1) };
430 if (my $err = $@) {
431 $self->log('err', $err);
432 }
433
434 # cleanup ressources on target host
435 my $nodename = PVE::INotify::nodename();
436
437 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'stop', $vmid, '--skiplock', '--migratedfrom', $nodename];
438 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
439 if (my $err = $@) {
440 $self->log('err', $err);
441 $self->{errors} = 1;
442 }
443 }
444
445 sub phase3 {
446 my ($self, $vmid) = @_;
447
448 my $volids = $self->{volumes};
449 return if $self->{phase2errors};
450
451 # destroy local copies
452 foreach my $volid (@$volids) {
453 eval { PVE::Storage::vdisk_free($self->{storecfg}, $volid); };
454 if (my $err = $@) {
455 $self->log('err', "removing local copy of '$volid' failed - $err");
456 $self->{errors} = 1;
457 last if $err =~ /^interrupted by signal$/;
458 }
459 }
460 }
461
462 sub phase3_cleanup {
463 my ($self, $vmid, $err) = @_;
464
465 my $conf = $self->{vmconf};
466 return if $self->{phase2errors};
467
468 # move config to remote node
469 my $conffile = PVE::QemuServer::config_file($vmid);
470 my $newconffile = PVE::QemuServer::config_file($vmid, $self->{node});
471
472 die "Failed to move config to node '$self->{node}' - rename failed: $!\n"
473 if !rename($conffile, $newconffile);
474
475 # now that config file is move, we can resume vm on target if livemigrate
476 if ($self->{tunnel}) {
477 my $cmd = [@{$self->{rem_ssh}}, 'qm', 'resume', $vmid, '--skiplock'];
478 eval{ PVE::Tools::run_command($cmd, outfunc => sub {}, errfunc => sub {}) };
479 if (my $err = $@) {
480 $self->log('err', $err);
481 $self->{errors} = 1;
482 }
483 }
484
485 # always stop local VM
486 eval { PVE::QemuServer::vm_stop($self->{storecfg}, $vmid, 1, 1); };
487 if (my $err = $@) {
488 $self->log('err', "stopping vm failed - $err");
489 $self->{errors} = 1;
490 }
491
492 if ($self->{tunnel}) {
493 eval { finish_tunnel($self, $self->{tunnel}); };
494 if (my $err = $@) {
495 $self->log('err', $err);
496 $self->{errors} = 1;
497 }
498 }
499
500 # always deactivate volumes - avoid lvm LVs to be active on several nodes
501 eval {
502 my $vollist = PVE::QemuServer::get_vm_volumes($conf);
503 PVE::Storage::deactivate_volumes($self->{storecfg}, $vollist);
504 };
505 if (my $err = $@) {
506 $self->log('err', $err);
507 $self->{errors} = 1;
508 }
509
510 # clear migrate lock
511 my $cmd = [ @{$self->{rem_ssh}}, 'qm', 'unlock', $vmid ];
512 $self->cmd_logerr($cmd, errmsg => "failed to clear migrate lock");
513 }
514
515 sub final_cleanup {
516 my ($self, $vmid) = @_;
517
518 # nothing to do
519 }
520
521 1;