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