]> git.proxmox.com Git - qemu-server.git/blame - PVE/CLI/qm.pm
qm nbdstop: cope graceful with errors
[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;
f3e76e36 11use IO::Select;
7c2d9b40
TL
12use IO::Socket::UNIX;
13use JSON;
5f1dc9af 14use POSIX qw(strftime);
7c2d9b40
TL
15use Term::ReadLine;
16use URI::Escape;
f3e76e36 17
f3e76e36 18use PVE::Cluster;
520884de 19use PVE::Exception qw(raise_param_exc);
9e784b11 20use PVE::GuestHelpers;
7c2d9b40
TL
21use PVE::INotify;
22use PVE::JSONSchema qw(get_standard_option);
23use PVE::Network;
24use PVE::RPCEnvironment;
25use PVE::SafeSyslog;
26use PVE::Tools qw(extract_param);
27
28use PVE::API2::Qemu::Agent;
29use PVE::API2::Qemu;
0a13e08e 30use PVE::QemuConfig;
e0fd2b2f 31use PVE::QemuServer::Drive;
d036e418 32use PVE::QemuServer::Helpers;
7c2d9b40 33use PVE::QemuServer::Agent qw(agent_available);
8653feeb 34use PVE::QemuServer::ImportDisk;
0a13e08e 35use PVE::QemuServer::Monitor qw(mon_cmd);
7cd9f6d7 36use PVE::QemuServer::OVF;
7c2d9b40 37use PVE::QemuServer;
f3e76e36
DM
38
39use PVE::CLIHandler;
f3e76e36
DM
40use base qw(PVE::CLIHandler);
41
42my $upid_exit = sub {
43 my $upid = shift;
44 my $status = PVE::Tools::upid_read_status($upid);
45 exit($status eq 'OK' ? 0 : -1);
46};
47
48my $nodename = PVE::INotify::nodename();
49
5e4035c7
DM
50sub setup_environment {
51 PVE::RPCEnvironment->setup_default_cli_env();
52}
53
f3e76e36
DM
54sub run_vnc_proxy {
55 my ($path) = @_;
56
57 my $c;
58 while ( ++$c < 10 && !-e $path ) { sleep(1); }
59
60 my $s = IO::Socket::UNIX->new(Peer => $path, Timeout => 120);
61
62 die "unable to connect to socket '$path' - $!" if !$s;
63
64 my $select = new IO::Select;
65
66 $select->add(\*STDIN);
67 $select->add($s);
68
69 my $timeout = 60*15; # 15 minutes
70
71 my @handles;
72 while ($select->count &&
73 scalar(@handles = $select->can_read ($timeout))) {
74 foreach my $h (@handles) {
75 my $buf;
76 my $n = $h->sysread($buf, 4096);
77
78 if ($h == \*STDIN) {
79 if ($n) {
80 syswrite($s, $buf);
81 } else {
82 exit(0);
83 }
84 } elsif ($h == $s) {
85 if ($n) {
86 syswrite(\*STDOUT, $buf);
87 } else {
88 exit(0);
89 }
90 }
91 }
92 }
93 exit(0);
94}
95
81fff836
DC
96sub print_recursive_hash {
97 my ($prefix, $hash, $key) = @_;
98
99 if (ref($hash) eq 'HASH') {
100 if (defined($key)) {
101 print "$prefix$key:\n";
102 }
103 foreach my $itemkey (keys %$hash) {
104 print_recursive_hash("\t$prefix", $hash->{$itemkey}, $itemkey);
105 }
106 } elsif (ref($hash) eq 'ARRAY') {
107 if (defined($key)) {
108 print "$prefix$key:\n";
109 }
110 foreach my $item (@$hash) {
111 print_recursive_hash("\t$prefix", $item);
112 }
113 } elsif (!ref($hash) && defined($hash)) {
114 if (defined($key)) {
115 print "$prefix$key: $hash\n";
116 } else {
117 print "$prefix$hash\n";
118 }
119 }
120}
121
f3e76e36
DM
122__PACKAGE__->register_method ({
123 name => 'showcmd',
124 path => 'showcmd',
125 method => 'GET',
126 description => "Show command line which is used to start the VM (debug info).",
127 parameters => {
128 additionalProperties => 0,
129 properties => {
335af808 130 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
16a01738
TL
131 pretty => {
132 description => "Puts each option on a new line to enhance human readability",
133 type => 'boolean',
134 optional => 1,
135 default => 0,
b14477e7
RV
136 },
137 snapshot => get_standard_option('pve-snapshot-name', {
138 description => "Fetch config values from given snapshot.",
139 optional => 1,
140 completion => sub {
141 my ($cmd, $pname, $cur, $args) = @_;
142 PVE::QemuConfig->snapshot_list($args->[0]);
143 }
144 }),
f3e76e36
DM
145 },
146 },
147 returns => { type => 'null'},
148 code => sub {
149 my ($param) = @_;
150
151 my $storecfg = PVE::Storage::config();
b14477e7 152 my $cmdline = PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}, $param->{snapshot});
16a01738 153
108899b4 154 $cmdline =~ s/ -/ \\\n -/g if $param->{pretty};
16a01738
TL
155
156 print "$cmdline\n";
f3e76e36
DM
157
158 return undef;
159 }});
160
161__PACKAGE__->register_method ({
162 name => 'status',
163 path => 'status',
164 method => 'GET',
165 description => "Show VM status.",
166 parameters => {
167 additionalProperties => 0,
168 properties => {
335af808 169 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
170 verbose => {
171 description => "Verbose output format",
172 type => 'boolean',
173 optional => 1,
174 }
175 },
176 },
177 returns => { type => 'null'},
178 code => sub {
179 my ($param) = @_;
180
181 # test if VM exists
ffda963f 182 my $conf = PVE::QemuConfig->load_config ($param->{vmid});
f3e76e36 183
12612b09 184 my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
f3e76e36
DM
185 my $stat = $vmstatus->{$param->{vmid}};
186 if ($param->{verbose}) {
187 foreach my $k (sort (keys %$stat)) {
188 next if $k eq 'cpu' || $k eq 'relcpu'; # always 0
189 my $v = $stat->{$k};
81fff836 190 print_recursive_hash("", $v, $k);
f3e76e36
DM
191 }
192 } else {
12612b09 193 my $status = $stat->{qmpstatus} || 'unknown';
f3e76e36
DM
194 print "status: $status\n";
195 }
196
197 return undef;
198 }});
199
200__PACKAGE__->register_method ({
201 name => 'vncproxy',
202 path => 'vncproxy',
203 method => 'PUT',
204 description => "Proxy VM VNC traffic to stdin/stdout",
205 parameters => {
206 additionalProperties => 0,
207 properties => {
335af808 208 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
209 },
210 },
211 returns => { type => 'null'},
212 code => sub {
213 my ($param) = @_;
214
215 my $vmid = $param->{vmid};
0a13e08e 216 PVE::QemuConfig::assert_config_exists_on_node($vmid);
d036e418 217 my $vnc_socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
f3e76e36
DM
218
219 if (my $ticket = $ENV{LC_PVE_TICKET}) { # NOTE: ssh on debian only pass LC_* variables
0a13e08e
SR
220 mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
221 mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
222 mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
f3e76e36 223 } else {
dc62a7fa 224 # FIXME: remove or allow to add tls-creds object, as x509 vnc param is removed with qemu 4??
0a13e08e 225 mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
f3e76e36
DM
226 }
227
228 run_vnc_proxy($vnc_socket);
229
230 return undef;
231 }});
232
233__PACKAGE__->register_method ({
234 name => 'unlock',
235 path => 'unlock',
236 method => 'PUT',
237 description => "Unlock the VM.",
238 parameters => {
239 additionalProperties => 0,
240 properties => {
335af808 241 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
f3e76e36
DM
242 },
243 },
244 returns => { type => 'null'},
245 code => sub {
246 my ($param) = @_;
247
248 my $vmid = $param->{vmid};
249
04096e7b 250 PVE::QemuConfig->lock_config ($vmid, sub {
ffda963f 251 my $conf = PVE::QemuConfig->load_config($vmid);
f3e76e36
DM
252 delete $conf->{lock};
253 delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
ffda963f 254 PVE::QemuConfig->write_config($vmid, $conf);
f3e76e36
DM
255 });
256
257 return undef;
258 }});
259
63a09370
AD
260__PACKAGE__->register_method ({
261 name => 'nbdstop',
262 path => 'nbdstop',
263 method => 'PUT',
264 description => "Stop embedded nbd server.",
265 parameters => {
266 additionalProperties => 0,
267 properties => {
268 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
269 },
270 },
271 returns => { type => 'null'},
272 code => sub {
273 my ($param) = @_;
274
275 my $vmid = $param->{vmid};
276
aa6ebf6a
TL
277 eval { PVE::QemuServer::nbd_stop($vmid) };
278 warn $@ if $@;
63a09370
AD
279
280 return undef;
281 }});
282
f3e76e36
DM
283__PACKAGE__->register_method ({
284 name => 'mtunnel',
285 path => 'mtunnel',
286 method => 'POST',
287 description => "Used by qmigrate - do not use manually.",
288 parameters => {
289 additionalProperties => 0,
290 properties => {},
291 },
292 returns => { type => 'null'},
293 code => sub {
294 my ($param) = @_;
295
296 if (!PVE::Cluster::check_cfs_quorum(1)) {
297 print "no quorum\n";
298 return undef;
299 }
300
79c9e079
FG
301 my $tunnel_write = sub {
302 my $text = shift;
303 chomp $text;
304 print "$text\n";
305 *STDOUT->flush();
306 };
307
308 $tunnel_write->("tunnel online");
309 $tunnel_write->("ver 1");
d8518469 310
e5caa02e 311 while (my $line = <STDIN>) {
f3e76e36 312 chomp $line;
bcb51ae8
FG
313 if ($line =~ /^quit$/) {
314 $tunnel_write->("OK");
315 last;
1d5aaa1d
FG
316 } elsif ($line =~ /^resume (\d+)$/) {
317 my $vmid = $1;
318 if (PVE::QemuServer::check_running($vmid, 1)) {
319 eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
320 if ($@) {
321 $tunnel_write->("ERR: resume failed - $@");
322 } else {
323 $tunnel_write->("OK");
324 }
325 } else {
326 $tunnel_write->("ERR: resume failed - VM $vmid not running");
327 }
bcb51ae8 328 }
f3e76e36
DM
329 }
330
331 return undef;
332 }});
333
334__PACKAGE__->register_method ({
335 name => 'wait',
336 path => 'wait',
337 method => 'GET',
338 description => "Wait until the VM is stopped.",
339 parameters => {
340 additionalProperties => 0,
341 properties => {
335af808 342 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
343 timeout => {
344 description => "Timeout in seconds. Default is to wait forever.",
345 type => 'integer',
346 minimum => 1,
347 optional => 1,
348 }
349 },
350 },
351 returns => { type => 'null'},
352 code => sub {
353 my ($param) = @_;
354
355 my $vmid = $param->{vmid};
356 my $timeout = $param->{timeout};
357
358 my $pid = PVE::QemuServer::check_running ($vmid);
359 return if !$pid;
360
361 print "waiting until VM $vmid stopps (PID $pid)\n";
362
363 my $count = 0;
364 while ((!$timeout || ($count < $timeout)) && PVE::QemuServer::check_running ($vmid)) {
365 $count++;
366 sleep 1;
367 }
368
369 die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
370
371 return undef;
372 }});
373
374__PACKAGE__->register_method ({
375 name => 'monitor',
376 path => 'monitor',
377 method => 'POST',
378 description => "Enter Qemu Monitor interface.",
379 parameters => {
380 additionalProperties => 0,
381 properties => {
335af808 382 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
383 },
384 },
385 returns => { type => 'null'},
386 code => sub {
387 my ($param) = @_;
388
389 my $vmid = $param->{vmid};
390
ffda963f 391 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
f3e76e36
DM
392
393 print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
394
395 my $term = new Term::ReadLine ('qm');
396
397 my $input;
398 while (defined ($input = $term->readline('qm> '))) {
399 chomp $input;
400
401 next if $input =~ m/^\s*$/;
402
403 last if $input =~ m/^\s*q(uit)?\s*$/;
404
405 eval {
0a13e08e 406 print PVE::QemuServer::Monitor::hmp_cmd($vmid, $input);
f3e76e36
DM
407 };
408 print "ERROR: $@" if $@;
409 }
410
411 return undef;
412
413 }});
414
415__PACKAGE__->register_method ({
416 name => 'rescan',
417 path => 'rescan',
418 method => 'POST',
419 description => "Rescan all storages and update disk sizes and unused disk images.",
420 parameters => {
421 additionalProperties => 0,
422 properties => {
335af808
DM
423 vmid => get_standard_option('pve-vmid', {
424 optional => 1,
425 completion => \&PVE::QemuServer::complete_vmid,
426 }),
9224dcee
TL
427 dryrun => {
428 type => 'boolean',
429 optional => 1,
430 default => 0,
dc02254e 431 description => 'Do not actually write changes out to VM config(s).',
9224dcee 432 },
f3e76e36
DM
433 },
434 },
435 returns => { type => 'null'},
436 code => sub {
437 my ($param) = @_;
438
9224dcee
TL
439 my $dryrun = $param->{dryrun};
440
441 print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
442
443 PVE::QemuServer::rescan($param->{vmid}, 0, $dryrun);
f3e76e36
DM
444
445 return undef;
446 }});
447
8653feeb
EK
448__PACKAGE__->register_method ({
449 name => 'importdisk',
450 path => 'importdisk',
451 method => 'POST',
452 description => "Import an external disk image as an unused disk in a VM. The
453 image format has to be supported by qemu-img(1).",
454 parameters => {
455 additionalProperties => 0,
456 properties => {
457 vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
458 source => {
459 description => 'Path to the disk image to import',
460 type => 'string',
461 optional => 0,
462 },
463 storage => get_standard_option('pve-storage-id', {
464 description => 'Target storage ID',
465 completion => \&PVE::QemuServer::complete_storage,
466 optional => 0,
467 }),
468 format => {
469 type => 'string',
470 description => 'Target format',
471 enum => [ 'raw', 'qcow2', 'vmdk' ],
472 optional => 1,
473 },
474 },
475 },
476 returns => { type => 'null'},
477 code => sub {
478 my ($param) = @_;
479
480 my $vmid = extract_param($param, 'vmid');
481 my $source = extract_param($param, 'source');
482 my $storeid = extract_param($param, 'storage');
483 my $format = extract_param($param, 'format');
484
485 my $vm_conf = PVE::QemuConfig->load_config($vmid);
486 PVE::QemuConfig->check_lock($vm_conf);
487 die "$source: non-existent or non-regular file\n" if (! -f $source);
c7db1e40 488
8653feeb
EK
489 my $storecfg = PVE::Storage::config();
490 PVE::Storage::storage_check_enabled($storecfg, $storeid);
491
c75bf161 492 my $target_storage_config = PVE::Storage::storage_config($storecfg, $storeid);
c7db1e40
EK
493 die "storage $storeid does not support vm images\n"
494 if !$target_storage_config->{content}->{images};
495
c75bf161
TL
496 print "importing disk '$source' to VM $vmid ...\n";
497 my ($drive_id, $volid) = PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
498 print "Successfully imported disk as '$drive_id:$volid'\n";
8653feeb
EK
499
500 return undef;
501 }});
502
f3e76e36
DM
503__PACKAGE__->register_method ({
504 name => 'terminal',
505 path => 'terminal',
506 method => 'POST',
507 description => "Open a terminal using a serial device (The VM need to have a serial device configured, for example 'serial0: socket')",
508 parameters => {
509 additionalProperties => 0,
510 properties => {
335af808 511 vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid_running }),
f3e76e36
DM
512 iface => {
513 description => "Select the serial device. By default we simply use the first suitable device.",
514 type => 'string',
515 optional => 1,
516 enum => [qw(serial0 serial1 serial2 serial3)],
aa320bcd
WB
517 },
518 escape => {
519 description => "Escape character.",
520 type => 'string',
521 optional => 1,
522 default => '^O',
523 },
f3e76e36
DM
524 },
525 },
526 returns => { type => 'null'},
527 code => sub {
528 my ($param) = @_;
529
530 my $vmid = $param->{vmid};
531
aa320bcd
WB
532 my $escape = $param->{escape} // '^O';
533 if ($escape =~ /^\^([\x40-\x7a])$/) {
534 $escape = ord($1) & 0x1F;
535 } elsif ($escape =~ /^0x[0-9a-f]+$/i) {
536 $escape = hex($escape);
537 } elsif ($escape =~ /^[0-9]+$/) {
538 $escape = int($escape);
539 } else {
540 die "invalid escape character definition: $escape\n";
541 }
542 my $escapemsg = '';
543 if ($escape) {
544 $escapemsg = sprintf(' (press Ctrl+%c to exit)', $escape+0x40);
545 $escape = sprintf(',escape=0x%x', $escape);
546 } else {
547 $escape = '';
548 }
549
ffda963f 550 my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
f3e76e36
DM
551
552 my $iface = $param->{iface};
553
554 if ($iface) {
555 die "serial interface '$iface' is not configured\n" if !$conf->{$iface};
556 die "wrong serial type on interface '$iface'\n" if $conf->{$iface} ne 'socket';
557 } else {
558 foreach my $opt (qw(serial0 serial1 serial2 serial3)) {
559 if ($conf->{$opt} && ($conf->{$opt} eq 'socket')) {
560 $iface = $opt;
561 last;
562 }
563 }
564 die "unable to find a serial interface\n" if !$iface;
565 }
566
567 die "VM $vmid not running\n" if !PVE::QemuServer::check_running($vmid);
568
569 my $socket = "/var/run/qemu-server/${vmid}.$iface";
570
aa320bcd 571 my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0$escape";
f3e76e36 572
aa320bcd 573 print "starting serial terminal on interface ${iface}${escapemsg}\n";
f3e76e36
DM
574
575 system($cmd);
576
577 return undef;
578 }});
579
7cd9f6d7
EK
580__PACKAGE__->register_method ({
581 name => 'importovf',
582 path => 'importovf',
583 description => "Create a new VM using parameters read from an OVF manifest",
584 parameters => {
585 additionalProperties => 0,
586 properties => {
587 vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
588 manifest => {
589 type => 'string',
590 description => 'path to the ovf file',
591 },
592 storage => get_standard_option('pve-storage-id', {
593 description => 'Target storage ID',
594 completion => \&PVE::QemuServer::complete_storage,
595 optional => 0,
596 }),
597 format => {
598 type => 'string',
599 description => 'Target format',
600 enum => [ 'raw', 'qcow2', 'vmdk' ],
601 optional => 1,
602 },
603 dryrun => {
604 type => 'boolean',
605 description => 'Print a parsed representation of the extracted OVF parameters, but do not create a VM',
606 optional => 1,
f6306646 607 }
7cd9f6d7
EK
608 },
609 },
b533b995 610 returns => { type => 'null' },
7cd9f6d7
EK
611 code => sub {
612 my ($param) = @_;
613
614 my $vmid = PVE::Tools::extract_param($param, 'vmid');
615 my $ovf_file = PVE::Tools::extract_param($param, 'manifest');
616 my $storeid = PVE::Tools::extract_param($param, 'storage');
617 my $format = PVE::Tools::extract_param($param, 'format');
618 my $dryrun = PVE::Tools::extract_param($param, 'dryrun');
619
620 die "$ovf_file: non-existent or non-regular file\n" if (! -f $ovf_file);
621 my $storecfg = PVE::Storage::config();
622 PVE::Storage::storage_check_enabled($storecfg, $storeid);
623
624 my $parsed = PVE::QemuServer::OVF::parse_ovf($ovf_file);
625
626 if ($dryrun) {
0f80f1ab
WB
627 print to_json($parsed, { pretty => 1, canonical => 1});
628 return;
7cd9f6d7
EK
629 }
630
73a4470a
TL
631 eval { PVE::QemuConfig->create_and_lock_config($vmid) };
632 die "Reserving empty config for OVF import to VM $vmid failed: $@" if $@;
7cd9f6d7 633
439390e8
DJ
634 my $conf = PVE::QemuConfig->load_config($vmid);
635 die "Internal error: Expected 'create' lock in config of VM $vmid!"
636 if !PVE::QemuConfig->has_lock($conf, "create");
7cd9f6d7 637
439390e8
DJ
638 $conf->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
639 $conf->{memory} = $parsed->{qm}->{memory} if defined($parsed->{qm}->{memory});
640 $conf->{cores} = $parsed->{qm}->{cores} if defined($parsed->{qm}->{cores});
7cd9f6d7 641
439390e8
DJ
642 eval {
643 # order matters, as do_import() will load_config() internally
644 $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
645 $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
646 PVE::QemuConfig->write_config($vmid, $conf);
7cd9f6d7 647
439390e8
DJ
648 foreach my $disk (@{ $parsed->{disks} }) {
649 my ($file, $drive) = ($disk->{backing_file}, $disk->{disk_address});
5600c5b2
TL
650 PVE::QemuServer::ImportDisk::do_import($file, $vmid, $storeid, {
651 drive_name => $drive,
652 format => $format,
653 skiplock => 1,
654 });
7cd9f6d7 655 }
439390e8
DJ
656
657 # reload after disks entries have been created
658 $conf = PVE::QemuConfig->load_config($vmid);
e0fd2b2f 659 my $firstdisk = PVE::QemuServer::Drive::resolve_first_disk($conf);
439390e8
DJ
660 $conf->{bootdisk} = $firstdisk if $firstdisk;
661 PVE::QemuConfig->write_config($vmid, $conf);
7cd9f6d7
EK
662 };
663
439390e8
DJ
664 my $err = $@;
665 if ($err) {
666 my $skiplock = 1;
667 # eval for additional safety in error path
b04ea584 668 eval { PVE::QemuServer::destroy_vm($storecfg, $vmid, $skiplock) };
439390e8
DJ
669 warn "Could not destroy VM $vmid: $@" if "$@";
670 die "import failed - $err";
671 }
73a4470a
TL
672
673 PVE::QemuConfig->remove_lock($vmid, "create");
5d942f5a
EK
674
675 return undef;
7cd9f6d7
EK
676
677 }
678});
788a6a35 679
520884de
DC
680__PACKAGE__->register_method({
681 name => 'exec',
682 path => 'exec',
683 method => 'POST',
684 protected => 1,
685 description => "Executes the given command via the guest agent",
686 parameters => {
687 additionalProperties => 0,
688 properties => {
689 node => get_standard_option('pve-node'),
690 vmid => get_standard_option('pve-vmid', {
691 completion => \&PVE::QemuServer::complete_vmid_running }),
692 synchronous => {
693 type => 'boolean',
694 optional => 1,
695 default => 1,
696 description => "If set to off, returns the pid immediately instead of waiting for the commmand to finish or the timeout.",
697 },
698 'timeout' => {
699 type => 'integer',
700 description => "The maximum time to wait synchronously for the command to finish. If reached, the pid gets returned. Set to 0 to deactivate",
701 minimum => 0,
702 optional => 1,
703 default => 30,
704 },
d8f61794
SR
705 'pass-stdin' => {
706 type => 'boolean',
109a0950 707 description => "When set, read STDIN until EOF and forward to guest agent via 'input-data' (usually treated as STDIN to process launched by guest agent). Allows maximal 1 MiB.",
d8f61794
SR
708 optional => 1,
709 default => 0,
710 },
520884de
DC
711 'extra-args' => get_standard_option('extra-args'),
712 },
713 },
714 returns => {
715 type => 'object',
716 },
717 code => sub {
718 my ($param) = @_;
719
720 my $vmid = $param->{vmid};
721 my $sync = $param->{synchronous} // 1;
d8f61794 722 my $pass_stdin = $param->{'pass-stdin'};
520884de
DC
723 if (defined($param->{timeout}) && !$sync) {
724 raise_param_exc({ synchronous => "needs to be set for 'timeout'"});
725 }
726
d8f61794
SR
727 my $input_data = undef;
728 if ($pass_stdin) {
729 $input_data = '';
730 while (my $line = <STDIN>) {
731 $input_data .= $line;
732 if (length($input_data) > 1024*1024) {
733 # not sure how QEMU handles large amounts of data being
734 # passed into the QMP socket, so limit to be safe
735 die "'input-data' (STDIN) is limited to 1 MiB, aborting\n";
736 }
737 }
738 }
739
740 my $args = $param->{'extra-args'};
741 $args = undef if !$args || !@$args;
742
743 my $res = PVE::QemuServer::Agent::qemu_exec($vmid, $input_data, $args);
520884de
DC
744
745 if ($sync) {
746 my $pid = $res->{pid};
747 my $timeout = $param->{timeout} // 30;
748 my $starttime = time();
749
750 while ($timeout == 0 || (time() - $starttime) < $timeout) {
751 my $out = PVE::QemuServer::Agent::qemu_exec_status($vmid, $pid);
752 if ($out->{exited}) {
753 $res = $out;
754 last;
755 }
756 sleep 1;
757 }
758
759 if (!$res->{exited}) {
760 warn "timeout reached, returning pid\n";
761 }
762 }
763
764 return { result => $res };
765 }});
766
3ea84aeb
DC
767__PACKAGE__->register_method({
768 name => 'cleanup',
769 path => 'cleanup',
770 method => 'POST',
771 protected => 1,
772 description => "Cleans up resources like tap devices, vgpus, etc. Called after a vm shuts down, crashes, etc.",
773 parameters => {
774 additionalProperties => 0,
775 properties => {
776 node => get_standard_option('pve-node'),
777 vmid => get_standard_option('pve-vmid', {
778 completion => \&PVE::QemuServer::complete_vmid_running }),
779 'clean-shutdown' => {
780 type => 'boolean',
781 description => "Indicates if qemu shutdown cleanly.",
782 },
783 'guest-requested' => {
784 type => 'boolean',
785 description => "Indicates if the shutdown was requested by the guest or via qmp.",
786 },
787 },
788 },
789 returns => { type => 'null', },
790 code => sub {
791 my ($param) = @_;
792
793 my $vmid = $param->{vmid};
794 my $clean = $param->{'clean-shutdown'};
795 my $guest = $param->{'guest-requested'};
64457ed4 796 my $restart = 0;
3ea84aeb 797
0f56fff2
DC
798 # return if we do not have the config anymore
799 return if !-f PVE::QemuConfig->config_file($vmid);
800
3ea84aeb
DC
801 my $storecfg = PVE::Storage::config();
802 warn "Starting cleanup for $vmid\n";
803
804 PVE::QemuConfig->lock_config($vmid, sub {
805 my $conf = PVE::QemuConfig->load_config ($vmid);
806 my $pid = PVE::QemuServer::check_running ($vmid);
807 die "vm still running\n" if $pid;
808
809 if (!$clean) {
810 # we have to cleanup the tap devices after a crash
811
812 foreach my $opt (keys %$conf) {
813 next if $opt !~ m/^net(\d)+$/;
814 my $interface = $1;
815 PVE::Network::tap_unplug("tap${vmid}i${interface}");
816 }
817 }
818
819 if (!$clean || $guest) {
820 # vm was shutdown from inside the guest or crashed, doing api cleanup
821 PVE::QemuServer::vm_stop_cleanup($storecfg, $vmid, $conf, 0, 0);
822 }
9e784b11 823 PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-stop');
64457ed4
DC
824
825 $restart = eval { PVE::QemuServer::clear_reboot_request($vmid) };
826 warn $@ if $@;
3ea84aeb
DC
827 });
828
829 warn "Finished cleanup for $vmid\n";
830
64457ed4
DC
831 if ($restart) {
832 warn "Restarting VM $vmid\n";
833 PVE::API2::Qemu->vm_start({
834 vmid => $vmid,
835 node => $nodename,
836 });
837 }
838
3ea84aeb
DC
839 return undef;
840 }});
841
788a6a35
DM
842my $print_agent_result = sub {
843 my ($data) = @_;
844
520884de 845 my $result = $data->{result} // $data;
788a6a35
DM
846 return if !defined($result);
847
848 my $class = ref($result);
849
850 if (!$class) {
851 chomp $result;
852 return if $result =~ m/^\s*$/;
853 print "$result\n";
854 return;
855 }
856
857 if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
858 return;
859 }
860
861 print to_json($result, { pretty => 1, canonical => 1});
862};
863
3351aacc
WB
864sub param_mapping {
865 my ($name) = @_;
866
867 my $ssh_key_map = ['sshkeys', sub {
868 return URI::Escape::uri_escape(PVE::Tools::file_get_contents($_[0]));
869 }];
3dba118c 870 my $cipassword_map = PVE::CLIHandler::get_standard_mapping('pve-password', { name => 'cipassword' });
8593cbe4 871 my $password_map = PVE::CLIHandler::get_standard_mapping('pve-password');
3351aacc 872 my $mapping = {
29d1f147
WB
873 'update_vm' => [$ssh_key_map, $cipassword_map],
874 'create_vm' => [$ssh_key_map, $cipassword_map],
8593cbe4 875 'set-user-password' => [$password_map],
3351aacc
WB
876 };
877
878 return $mapping->{$name};
879}
880
f3e76e36
DM
881our $cmddef = {
882 list => [ "PVE::API2::Qemu", 'vmlist', [],
883 { node => $nodename }, sub {
884 my $vmlist = shift;
885
886 exit 0 if (!scalar(@$vmlist));
887
888 printf "%10s %-20s %-10s %-10s %12s %-10s\n",
889 qw(VMID NAME STATUS MEM(MB) BOOTDISK(GB) PID);
890
891 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
892 printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
12612b09 893 $rec->{qmpstatus} || $rec->{status},
f3e76e36
DM
894 ($rec->{maxmem} || 0)/(1024*1024),
895 ($rec->{maxdisk} || 0)/(1024*1024*1024),
896 $rec->{pid}||0;
897 }
898
899
900 } ],
901
902 create => [ "PVE::API2::Qemu", 'create_vm', ['vmid'], { node => $nodename }, $upid_exit ],
903
904 destroy => [ "PVE::API2::Qemu", 'destroy_vm', ['vmid'], { node => $nodename }, $upid_exit ],
905
906 clone => [ "PVE::API2::Qemu", 'clone_vm', ['vmid', 'newid'], { node => $nodename }, $upid_exit ],
907
908 migrate => [ "PVE::API2::Qemu", 'migrate_vm', ['vmid', 'target'], { node => $nodename }, $upid_exit ],
909
910 set => [ "PVE::API2::Qemu", 'update_vm', ['vmid'], { node => $nodename } ],
911
912 resize => [ "PVE::API2::Qemu", 'resize_vm', ['vmid', 'disk', 'size'], { node => $nodename } ],
913
914 move_disk => [ "PVE::API2::Qemu", 'move_vm_disk', ['vmid', 'disk', 'storage'], { node => $nodename }, $upid_exit ],
915
916 unlink => [ "PVE::API2::Qemu", 'unlink', ['vmid'], { node => $nodename } ],
917
918 config => [ "PVE::API2::Qemu", 'vm_config', ['vmid'],
919 { node => $nodename }, sub {
920 my $config = shift;
921 foreach my $k (sort (keys %$config)) {
922 next if $k eq 'digest';
923 my $v = $config->{$k};
924 if ($k eq 'description') {
925 $v = PVE::Tools::encode_text($v);
926 }
927 print "$k: $v\n";
928 }
929 }],
930
5c39708e 931 pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
f3e76e36
DM
932 showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
933
934 status => [ __PACKAGE__, 'status', ['vmid']],
935
936 snapshot => [ "PVE::API2::Qemu", 'snapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
937
938 delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
939
90ec74ea 940 listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree],
265db461 941
f3e76e36
DM
942 rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
943
944 template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
945
946 start => [ "PVE::API2::Qemu", 'vm_start', ['vmid'], { node => $nodename } , $upid_exit ],
947
948 stop => [ "PVE::API2::Qemu", 'vm_stop', ['vmid'], { node => $nodename }, $upid_exit ],
949
950 reset => [ "PVE::API2::Qemu", 'vm_reset', ['vmid'], { node => $nodename }, $upid_exit ],
951
952 shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
953
165411f0
DC
954 reboot => [ "PVE::API2::Qemu", 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit ],
955
f3e76e36
DM
956 suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
957
958 resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
959
960 sendkey => [ "PVE::API2::Qemu", 'vm_sendkey', ['vmid', 'key'], { node => $nodename } ],
961
962 vncproxy => [ __PACKAGE__, 'vncproxy', ['vmid']],
963
964 wait => [ __PACKAGE__, 'wait', ['vmid']],
965
966 unlock => [ __PACKAGE__, 'unlock', ['vmid']],
967
968 rescan => [ __PACKAGE__, 'rescan', []],
969
970 monitor => [ __PACKAGE__, 'monitor', ['vmid']],
971
bf744e94 972 agent => { alias => 'guest cmd' },
d1a47427 973
34e4c0aa 974 guest => {
bf744e94 975 cmd => [ "PVE::API2::Qemu::Agent", 'agent', ['vmid', 'command'], { node => $nodename }, $print_agent_result ],
8593cbe4 976 passwd => [ "PVE::API2::Qemu::Agent", 'set-user-password', [ 'vmid', 'username' ], { node => $nodename }],
520884de
DC
977 exec => [ __PACKAGE__, 'exec', [ 'vmid', 'extra-args' ], { node => $nodename }, $print_agent_result],
978 'exec-status' => [ "PVE::API2::Qemu::Agent", 'exec-status', [ 'vmid', 'pid' ], { node => $nodename }, $print_agent_result],
8593cbe4
DC
979 },
980
f3e76e36
DM
981 mtunnel => [ __PACKAGE__, 'mtunnel', []],
982
63a09370
AD
983 nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
984
f3e76e36 985 terminal => [ __PACKAGE__, 'terminal', ['vmid']],
8653feeb
EK
986
987 importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
7cd9f6d7
EK
988
989 importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
990
3ea84aeb
DC
991 cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
992
1e1763e9
ML
993 cloudinit => {
994 dump => [ "PVE::API2::Qemu", 'cloudinit_generated_config_dump', ['vmid', 'type'], { node => $nodename }, sub {
995 my $data = shift;
996 print "$data\n";
997 }],
998 },
999
f3e76e36
DM
1000};
1001
10021;