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