]> git.proxmox.com Git - qemu-server.git/blame - PVE/CLI/qm.pm
qm mtunnel/migrate: add resume VMID command
[qemu-server.git] / PVE / CLI / qm.pm
CommitLineData
f3e76e36
DM
1package PVE::CLI::qm;
2
3use strict;
4use warnings;
5
6# Note: disable '+' prefix for Getopt::Long (for resize command)
7use Getopt::Long qw(:config no_getopt_compat);
8
9use Fcntl ':flock';
10use File::Path;
11use IO::Socket::UNIX;
12use IO::Select;
13
14use PVE::Tools qw(extract_param);
15use PVE::Cluster;
16use PVE::SafeSyslog;
17use PVE::INotify;
18use PVE::RPCEnvironment;
19use PVE::QemuServer;
8653feeb 20use PVE::QemuServer::ImportDisk;
f3e76e36 21use PVE::API2::Qemu;
788a6a35 22use JSON;
f3e76e36
DM
23use PVE::JSONSchema qw(get_standard_option);
24use Term::ReadLine;
25
26use PVE::CLIHandler;
27
28use base qw(PVE::CLIHandler);
29
30my $upid_exit = sub {
31 my $upid = shift;
32 my $status = PVE::Tools::upid_read_status($upid);
33 exit($status eq 'OK' ? 0 : -1);
34};
35
36my $nodename = PVE::INotify::nodename();
37
5e4035c7
DM
38sub setup_environment {
39 PVE::RPCEnvironment->setup_default_cli_env();
40}
41
f3e76e36
DM
42sub run_vnc_proxy {
43 my ($path) = @_;
44
45 my $c;
46 while ( ++$c < 10 && !-e $path ) { sleep(1); }
47
48 my $s = IO::Socket::UNIX->new(Peer => $path, Timeout => 120);
49
50 die "unable to connect to socket '$path' - $!" if !$s;
51
52 my $select = new IO::Select;
53
54 $select->add(\*STDIN);
55 $select->add($s);
56
57 my $timeout = 60*15; # 15 minutes
58
59 my @handles;
60 while ($select->count &&
61 scalar(@handles = $select->can_read ($timeout))) {
62 foreach my $h (@handles) {
63 my $buf;
64 my $n = $h->sysread($buf, 4096);
65
66 if ($h == \*STDIN) {
67 if ($n) {
68 syswrite($s, $buf);
69 } else {
70 exit(0);
71 }
72 } elsif ($h == $s) {
73 if ($n) {
74 syswrite(\*STDOUT, $buf);
75 } else {
76 exit(0);
77 }
78 }
79 }
80 }
81 exit(0);
82}
83
81fff836
DC
84sub print_recursive_hash {
85 my ($prefix, $hash, $key) = @_;
86
87 if (ref($hash) eq 'HASH') {
88 if (defined($key)) {
89 print "$prefix$key:\n";
90 }
91 foreach my $itemkey (keys %$hash) {
92 print_recursive_hash("\t$prefix", $hash->{$itemkey}, $itemkey);
93 }
94 } elsif (ref($hash) eq 'ARRAY') {
95 if (defined($key)) {
96 print "$prefix$key:\n";
97 }
98 foreach my $item (@$hash) {
99 print_recursive_hash("\t$prefix", $item);
100 }
101 } elsif (!ref($hash) && defined($hash)) {
102 if (defined($key)) {
103 print "$prefix$key: $hash\n";
104 } else {
105 print "$prefix$hash\n";
106 }
107 }
108}
109
f3e76e36
DM
110__PACKAGE__->register_method ({
111 name => 'showcmd',
112 path => 'showcmd',
113 method => 'GET',
114 description => "Show command line which is used to start the VM (debug info).",
115 parameters => {
116 additionalProperties => 0,
117 properties => {
335af808 118 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
119 },
120 },
121 returns => { type => 'null'},
122 code => sub {
123 my ($param) = @_;
124
125 my $storecfg = PVE::Storage::config();
126 print PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}) . "\n";
127
128 return undef;
129 }});
130
131__PACKAGE__->register_method ({
132 name => 'status',
133 path => 'status',
134 method => 'GET',
135 description => "Show VM status.",
136 parameters => {
137 additionalProperties => 0,
138 properties => {
335af808 139 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
140 verbose => {
141 description => "Verbose output format",
142 type => 'boolean',
143 optional => 1,
144 }
145 },
146 },
147 returns => { type => 'null'},
148 code => sub {
149 my ($param) = @_;
150
151 # test if VM exists
ffda963f 152 my $conf = PVE::QemuConfig->load_config ($param->{vmid});
f3e76e36 153
12612b09 154 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
f3e76e36
DM
155 my $stat = $vmstatus->{$param->{vmid}};
156 if ($param->{verbose}) {
157 foreach my $k (sort (keys %$stat)) {
158 next if $k eq 'cpu' || $k eq 'relcpu'; # always 0
159 my $v = $stat->{$k};
81fff836 160 print_recursive_hash("", $v, $k);
f3e76e36
DM
161 }
162 } else {
12612b09 163 my $status = $stat->{qmpstatus} || 'unknown';
f3e76e36
DM
164 print "status: $status\n";
165 }
166
167 return undef;
168 }});
169
170__PACKAGE__->register_method ({
171 name => 'vncproxy',
172 path => 'vncproxy',
173 method => 'PUT',
174 description => "Proxy VM VNC traffic to stdin/stdout",
175 parameters => {
176 additionalProperties => 0,
177 properties => {
335af808 178 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
179 },
180 },
181 returns => { type => 'null'},
182 code => sub {
183 my ($param) = @_;
184
185 my $vmid = $param->{vmid};
186 my $vnc_socket = PVE::QemuServer::vnc_socket($vmid);
187
188 if (my $ticket = $ENV{LC_PVE_TICKET}) { # NOTE: ssh on debian only pass LC_* variables
189 PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
190 PVE::QemuServer::vm_mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
191 PVE::QemuServer::vm_mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
192 } else {
193 PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,x509,password");
194 }
195
196 run_vnc_proxy($vnc_socket);
197
198 return undef;
199 }});
200
201__PACKAGE__->register_method ({
202 name => 'unlock',
203 path => 'unlock',
204 method => 'PUT',
205 description => "Unlock the VM.",
206 parameters => {
207 additionalProperties => 0,
208 properties => {
335af808 209 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
210 },
211 },
212 returns => { type => 'null'},
213 code => sub {
214 my ($param) = @_;
215
216 my $vmid = $param->{vmid};
217
04096e7b 218 PVE::QemuConfig->lock_config ($vmid, sub {
ffda963f 219 my $conf = PVE::QemuConfig->load_config($vmid);
f3e76e36
DM
220 delete $conf->{lock};
221 delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
ffda963f 222 PVE::QemuConfig->write_config($vmid, $conf);
f3e76e36
DM
223 });
224
225 return undef;
226 }});
227
63a09370
AD
228__PACKAGE__->register_method ({
229 name => 'nbdstop',
230 path => 'nbdstop',
231 method => 'PUT',
232 description => "Stop embedded nbd server.",
233 parameters => {
234 additionalProperties => 0,
235 properties => {
236 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
237 },
238 },
239 returns => { type => 'null'},
240 code => sub {
241 my ($param) = @_;
242
243 my $vmid = $param->{vmid};
244
245 PVE::QemuServer::nbd_stop($vmid);
246
247 return undef;
248 }});
249
f3e76e36
DM
250__PACKAGE__->register_method ({
251 name => 'mtunnel',
252 path => 'mtunnel',
253 method => 'POST',
254 description => "Used by qmigrate - do not use manually.",
255 parameters => {
256 additionalProperties => 0,
257 properties => {},
258 },
259 returns => { type => 'null'},
260 code => sub {
261 my ($param) = @_;
262
263 if (!PVE::Cluster::check_cfs_quorum(1)) {
264 print "no quorum\n";
265 return undef;
266 }
267
79c9e079
FG
268 my $tunnel_write = sub {
269 my $text = shift;
270 chomp $text;
271 print "$text\n";
272 *STDOUT->flush();
273 };
274
275 $tunnel_write->("tunnel online");
276 $tunnel_write->("ver 1");
d8518469 277
f3e76e36
DM
278 while (my $line = <>) {
279 chomp $line;
bcb51ae8
FG
280 if ($line =~ /^quit$/) {
281 $tunnel_write->("OK");
282 last;
1d5aaa1d
FG
283 } elsif ($line =~ /^resume (\d+)$/) {
284 my $vmid = $1;
285 if (PVE::QemuServer::check_running($vmid, 1)) {
286 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
287 if ($@) {
288 $tunnel_write->("ERR: resume failed - $@");
289 } else {
290 $tunnel_write->("OK");
291 }
292 } else {
293 $tunnel_write->("ERR: resume failed - VM $vmid not running");
294 }
bcb51ae8 295 }
f3e76e36
DM
296 }
297
298 return undef;
299 }});
300
301__PACKAGE__->register_method ({
302 name => 'wait',
303 path => 'wait',
304 method => 'GET',
305 description => "Wait until the VM is stopped.",
306 parameters => {
307 additionalProperties => 0,
308 properties => {
335af808 309 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
310 timeout => {
311 description => "Timeout in seconds. Default is to wait forever.",
312 type => 'integer',
313 minimum => 1,
314 optional => 1,
315 }
316 },
317 },
318 returns => { type => 'null'},
319 code => sub {
320 my ($param) = @_;
321
322 my $vmid = $param->{vmid};
323 my $timeout = $param->{timeout};
324
325 my $pid = PVE::QemuServer::check_running ($vmid);
326 return if !$pid;
327
328 print "waiting until VM $vmid stopps (PID $pid)\n";
329
330 my $count = 0;
331 while ((!$timeout || ($count < $timeout)) && PVE::QemuServer::check_running ($vmid)) {
332 $count++;
333 sleep 1;
334 }
335
336 die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
337
338 return undef;
339 }});
340
341__PACKAGE__->register_method ({
342 name => 'monitor',
343 path => 'monitor',
344 method => 'POST',
345 description => "Enter Qemu Monitor interface.",
346 parameters => {
347 additionalProperties => 0,
348 properties => {
335af808 349 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
350 },
351 },
352 returns => { type => 'null'},
353 code => sub {
354 my ($param) = @_;
355
356 my $vmid = $param->{vmid};
357
ffda963f 358 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
f3e76e36
DM
359
360 print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
361
362 my $term = new Term::ReadLine ('qm');
363
364 my $input;
365 while (defined ($input = $term->readline('qm> '))) {
366 chomp $input;
367
368 next if $input =~ m/^\s*$/;
369
370 last if $input =~ m/^\s*q(uit)?\s*$/;
371
372 eval {
373 print PVE::QemuServer::vm_human_monitor_command ($vmid, $input);
374 };
375 print "ERROR: $@" if $@;
376 }
377
378 return undef;
379
380 }});
381
382__PACKAGE__->register_method ({
383 name => 'rescan',
384 path => 'rescan',
385 method => 'POST',
386 description => "Rescan all storages and update disk sizes and unused disk images.",
387 parameters => {
388 additionalProperties => 0,
389 properties => {
335af808
DM
390 vmid => get_standard_option('pve-vmid', {
391 optional => 1,
392 completion => \&PVE::QemuServer::complete_vmid,
393 }),
f3e76e36
DM
394 },
395 },
396 returns => { type => 'null'},
397 code => sub {
398 my ($param) = @_;
399
400 PVE::QemuServer::rescan($param->{vmid});
401
402 return undef;
403 }});
404
8653feeb
EK
405__PACKAGE__->register_method ({
406 name => 'importdisk',
407 path => 'importdisk',
408 method => 'POST',
409 description => "Import an external disk image as an unused disk in a VM. The
410 image format has to be supported by qemu-img(1).",
411 parameters => {
412 additionalProperties => 0,
413 properties => {
414 vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
415 source => {
416 description => 'Path to the disk image to import',
417 type => 'string',
418 optional => 0,
419 },
420 storage => get_standard_option('pve-storage-id', {
421 description => 'Target storage ID',
422 completion => \&PVE::QemuServer::complete_storage,
423 optional => 0,
424 }),
425 format => {
426 type => 'string',
427 description => 'Target format',
428 enum => [ 'raw', 'qcow2', 'vmdk' ],
429 optional => 1,
430 },
431 },
432 },
433 returns => { type => 'null'},
434 code => sub {
435 my ($param) = @_;
436
437 my $vmid = extract_param($param, 'vmid');
438 my $source = extract_param($param, 'source');
439 my $storeid = extract_param($param, 'storage');
440 my $format = extract_param($param, 'format');
441
442 my $vm_conf = PVE::QemuConfig->load_config($vmid);
443 PVE::QemuConfig->check_lock($vm_conf);
444 die "$source: non-existent or non-regular file\n" if (! -f $source);
c7db1e40 445
8653feeb
EK
446 my $storecfg = PVE::Storage::config();
447 PVE::Storage::storage_check_enabled($storecfg, $storeid);
448
c7db1e40
EK
449 my $target_storage_config =
450 PVE::Storage::storage_config($storecfg, $storeid);
451 die "storage $storeid does not support vm images\n"
452 if !$target_storage_config->{content}->{images};
453
8653feeb
EK
454 PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
455
456 return undef;
457 }});
458
f3e76e36
DM
459__PACKAGE__->register_method ({
460 name => 'terminal',
461 path => 'terminal',
462 method => 'POST',
463 description => "Open a terminal using a serial device (The VM need to have a serial device configured, for example 'serial0: socket')",
464 parameters => {
465 additionalProperties => 0,
466 properties => {
335af808 467 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
468 iface => {
469 description => "Select the serial device. By default we simply use the first suitable device.",
470 type => 'string',
471 optional => 1,
472 enum => [qw(serial0 serial1 serial2 serial3)],
473 }
474 },
475 },
476 returns => { type => 'null'},
477 code => sub {
478 my ($param) = @_;
479
480 my $vmid = $param->{vmid};
481
ffda963f 482 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
f3e76e36
DM
483
484 my $iface = $param->{iface};
485
486 if ($iface) {
487 die "serial interface '$iface' is not configured\n" if !$conf->{$iface};
488 die "wrong serial type on interface '$iface'\n" if $conf->{$iface} ne 'socket';
489 } else {
490 foreach my $opt (qw(serial0 serial1 serial2 serial3)) {
491 if ($conf->{$opt} && ($conf->{$opt} eq 'socket')) {
492 $iface = $opt;
493 last;
494 }
495 }
496 die "unable to find a serial interface\n" if !$iface;
497 }
498
499 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
500
501 my $socket = "/var/run/qemu-server/${vmid}.$iface";
502
503 my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0,escape=0x0f";
504
505 print "starting serial terminal on interface $iface (press control-O to exit)\n";
506
507 system($cmd);
508
509 return undef;
510 }});
511
788a6a35
DM
512
513my $print_agent_result = sub {
514 my ($data) = @_;
515
516 my $result = $data->{result};
517 return if !defined($result);
518
519 my $class = ref($result);
520
521 if (!$class) {
522 chomp $result;
523 return if $result =~ m/^\s*$/;
524 print "$result\n";
525 return;
526 }
527
528 if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
529 return;
530 }
531
532 print to_json($result, { pretty => 1, canonical => 1});
533};
534
f3e76e36
DM
535our $cmddef = {
536 list => [ "PVE::API2::Qemu", 'vmlist', [],
537 { node => $nodename }, sub {
538 my $vmlist = shift;
539
540 exit 0 if (!scalar(@$vmlist));
541
542 printf "%10s %-20s %-10s %-10s %12s %-10s\n",
543 qw(VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID);
544
545 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
546 printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
12612b09 547 $rec->{qmpstatus} || $rec->{status},
f3e76e36
DM
548 ($rec->{maxmem} || 0)/(1024*1024),
549 ($rec->{maxdisk} || 0)/(1024*1024*1024),
550 $rec->{pid}||0;
551 }
552
553
554 } ],
555
556 create => [ "PVE::API2::Qemu", 'create_vm', ['vmid'], { node => $nodename }, $upid_exit ],
557
558 destroy => [ "PVE::API2::Qemu", 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
559
560 clone => [ "PVE::API2::Qemu", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
561
562 migrate => [ "PVE::API2::Qemu", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit ],
563
564 set => [ "PVE::API2::Qemu", 'update_vm', ['vmid'], { node => $nodename } ],
565
566 resize => [ "PVE::API2::Qemu", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
567
568 move_disk => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
569
570 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
571
572 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
573 { node => $nodename }, sub {
574 my $config = shift;
575 foreach my $k (sort (keys %$config)) {
576 next if $k eq 'digest';
577 my $v = $config->{$k};
578 if ($k eq 'description') {
579 $v = PVE::Tools::encode_text($v);
580 }
581 print "$k: $v\n";
582 }
583 }],
584
585 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'],
586 { node => $nodename }, sub {
587 my $data = shift;
588 foreach my $item (sort { $a->{key} cmp $b->{key}} @$data) {
589 my $k = $item->{key};
590 next if $k eq 'digest';
591 my $v = $item->{value};
592 my $p = $item->{pending};
593 if ($k eq 'description') {
594 $v = PVE::Tools::encode_text($v) if defined($v);
595 $p = PVE::Tools::encode_text($p) if defined($p);
596 }
597 if (defined($v)) {
598 if ($item->{delete}) {
599 print "del $k: $v\n";
600 } elsif (defined($p)) {
601 print "cur $k: $v\n";
602 print "new $k: $p\n";
603 } else {
604 print "cur $k: $v\n";
605 }
606 } elsif (defined($p)) {
607 print "new $k: $p\n";
608 }
609 }
610 }],
611
612 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
613
614 status => [ __PACKAGE__, 'status', ['vmid']],
615
616 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
617
618 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
619
265db461
DC
620 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename },
621 sub {
622 my $res = shift;
623 foreach my $e (@$res) {
624 my $headline = $e->{description} || 'no-description';
625 $headline =~ s/\n.*//sg;
626 my $parent = $e->{parent} // 'no-parent';
627 printf("%-20s %-20s %s\n", $e->{name}, $parent, $headline);
628 }
629 }],
630
f3e76e36
DM
631 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
632
633 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
634
635 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
636
637 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
638
639 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
640
641 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
642
643 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
644
645 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
646
647 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
648
649 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
650
651 wait => [ __PACKAGE__, 'wait', ['vmid']],
652
653 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
654
655 rescan => [ __PACKAGE__, 'rescan', []],
656
657 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
658
ee2ff074 659 agent => [ "PVE::API2::Qemu", 'agent', ['vmid', 'command'],
788a6a35 660 { node => $nodename }, $print_agent_result ],
d1a47427 661
f3e76e36
DM
662 mtunnel => [ __PACKAGE__, 'mtunnel', []],
663
63a09370
AD
664 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
665
f3e76e36 666 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
8653feeb
EK
667
668 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
f3e76e36
DM
669};
670
6711;