use File::Path;
use IO::Socket::UNIX;
use IO::Select;
+use URI::Escape;
use PVE::Tools qw(extract_param);
use PVE::Cluster;
use PVE::SafeSyslog;
use PVE::INotify;
use PVE::RPCEnvironment;
+use PVE::Exception qw(raise_param_exc);
+use PVE::Network;
use PVE::QemuServer;
use PVE::QemuServer::ImportDisk;
use PVE::QemuServer::OVF;
+use PVE::QemuServer::Agent qw(agent_available);
use PVE::API2::Qemu;
+use PVE::API2::Qemu::Agent;
use JSON;
use PVE::JSONSchema qw(get_standard_option);
use Term::ReadLine;
-use Data::Dumper;
use PVE::CLIHandler;
additionalProperties => 0,
properties => {
vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
+ pretty => {
+ description => "Puts each option on a new line to enhance human readability",
+ type => 'boolean',
+ optional => 1,
+ default => 0,
+ },
+ snapshot => get_standard_option('pve-snapshot-name', {
+ description => "Fetch config values from given snapshot.",
+ optional => 1,
+ completion => sub {
+ my ($cmd, $pname, $cur, $args) = @_;
+ PVE::QemuConfig->snapshot_list($args->[0]);
+ }
+ }),
},
},
returns => { type => 'null'},
my ($param) = @_;
my $storecfg = PVE::Storage::config();
- print PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}) . "\n";
+ my $cmdline = PVE::QemuServer::vm_commandline($storecfg, $param->{vmid}, $param->{snapshot});
+
+ $cmdline =~ s/ -/ \\\n -/g if $param->{pretty};
+
+ print "$cmdline\n";
return undef;
}});
$tunnel_write->("tunnel online");
$tunnel_write->("ver 1");
- while (my $line = <>) {
+ while (my $line = <STDIN>) {
chomp $line;
if ($line =~ /^quit$/) {
$tunnel_write->("OK");
optional => 1,
completion => \&PVE::QemuServer::complete_vmid,
}),
+ dryrun => {
+ type => 'boolean',
+ optional => 1,
+ default => 0,
+ description => 'Do not actually write changes out to VM config(s).',
+ },
},
},
returns => { type => 'null'},
code => sub {
my ($param) = @_;
- PVE::QemuServer::rescan($param->{vmid});
+ my $dryrun = $param->{dryrun};
+
+ print "NOTE: running in dry-run mode, won't write changes out!\n" if $dryrun;
+
+ PVE::QemuServer::rescan($param->{vmid}, 0, $dryrun);
return undef;
}});
type => 'string',
optional => 1,
enum => [qw(serial0 serial1 serial2 serial3)],
- }
+ },
+ escape => {
+ description => "Escape character.",
+ type => 'string',
+ optional => 1,
+ default => '^O',
+ },
},
},
returns => { type => 'null'},
my $vmid = $param->{vmid};
+ my $escape = $param->{escape} // '^O';
+ if ($escape =~ /^\^([\x40-\x7a])$/) {
+ $escape = ord($1) & 0x1F;
+ } elsif ($escape =~ /^0x[0-9a-f]+$/i) {
+ $escape = hex($escape);
+ } elsif ($escape =~ /^[0-9]+$/) {
+ $escape = int($escape);
+ } else {
+ die "invalid escape character definition: $escape\n";
+ }
+ my $escapemsg = '';
+ if ($escape) {
+ $escapemsg = sprintf(' (press Ctrl+%c to exit)', $escape+0x40);
+ $escape = sprintf(',escape=0x%x', $escape);
+ } else {
+ $escape = '';
+ }
+
my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
my $iface = $param->{iface};
my $socket = "/var/run/qemu-server/${vmid}.$iface";
- my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0,escape=0x0f";
+ my $cmd = "socat UNIX-CONNECT:$socket STDIO,raw,echo=0$escape";
- print "starting serial terminal on interface $iface (press control-O to exit)\n";
+ print "starting serial terminal on interface ${iface}${escapemsg}\n";
system($cmd);
type => 'boolean',
description => 'Print a parsed representation of the extracted OVF parameters, but do not create a VM',
optional => 1,
- }
+ }
},
},
- returns => { type => 'string'},
+ returns => { type => 'null' },
code => sub {
my ($param) = @_;
my $parsed = PVE::QemuServer::OVF::parse_ovf($ovf_file);
if ($dryrun) {
- print Dumper($parsed);
- exit(0);
+ print to_json($parsed, { pretty => 1, canonical => 1});
+ return;
}
$param->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
eval {
# order matters, as do_import() will load_config() internally
+ $conf->{vmgenid} = PVE::QemuServer::generate_uuid();
$conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
PVE::QemuConfig->write_config($vmid, $conf);
my $firstdisk = PVE::QemuServer::resolve_first_disk($conf);
$conf->{bootdisk} = $firstdisk if $firstdisk;
PVE::QemuConfig->write_config($vmid, $conf);
- };
+ };
my $err = $@;
if ($err) {
eval { PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock); };
die "import failed - $err";
}
-
};
my $wait_for_lock = 1;
- return PVE::QemuConfig->lock_config_full($vmid, $wait_for_lock, $importfn);
+ PVE::QemuConfig->lock_config_full($vmid, $wait_for_lock, $importfn);
+
+ return undef;
}
});
+__PACKAGE__->register_method({
+ name => 'exec',
+ path => 'exec',
+ method => 'POST',
+ protected => 1,
+ description => "Executes the given command via the guest agent",
+ parameters => {
+ additionalProperties => 0,
+ properties => {
+ node => get_standard_option('pve-node'),
+ vmid => get_standard_option('pve-vmid', {
+ completion => \&PVE::QemuServer::complete_vmid_running }),
+ synchronous => {
+ type => 'boolean',
+ optional => 1,
+ default => 1,
+ description => "If set to off, returns the pid immediately instead of waiting for the commmand to finish or the timeout.",
+ },
+ 'timeout' => {
+ type => 'integer',
+ description => "The maximum time to wait synchronously for the command to finish. If reached, the pid gets returned. Set to 0 to deactivate",
+ minimum => 0,
+ optional => 1,
+ default => 30,
+ },
+ 'extra-args' => get_standard_option('extra-args'),
+ },
+ },
+ returns => {
+ type => 'object',
+ },
+ code => sub {
+ my ($param) = @_;
+
+ my $vmid = $param->{vmid};
+ my $sync = $param->{synchronous} // 1;
+ if (!$param->{'extra-args'} || !@{$param->{'extra-args'}}) {
+ raise_param_exc( { 'extra-args' => "No command given" });
+ }
+ if (defined($param->{timeout}) && !$sync) {
+ raise_param_exc({ synchronous => "needs to be set for 'timeout'"});
+ }
+
+ my $res = PVE::QemuServer::Agent::qemu_exec($vmid, $param->{'extra-args'});
+
+ if ($sync) {
+ my $pid = $res->{pid};
+ my $timeout = $param->{timeout} // 30;
+ my $starttime = time();
+
+ while ($timeout == 0 || (time() - $starttime) < $timeout) {
+ my $out = PVE::QemuServer::Agent::qemu_exec_status($vmid, $pid);
+ if ($out->{exited}) {
+ $res = $out;
+ last;
+ }
+ sleep 1;
+ }
+
+ if (!$res->{exited}) {
+ warn "timeout reached, returning pid\n";
+ }
+ }
+
+ return { result => $res };
+ }});
+
+__PACKAGE__->register_method({
+ name => 'cleanup',
+ path => 'cleanup',
+ method => 'POST',
+ protected => 1,
+ description => "Cleans up resources like tap devices, vgpus, etc. Called after a vm shuts down, crashes, etc.",
+ parameters => {
+ additionalProperties => 0,
+ properties => {
+ node => get_standard_option('pve-node'),
+ vmid => get_standard_option('pve-vmid', {
+ completion => \&PVE::QemuServer::complete_vmid_running }),
+ 'clean-shutdown' => {
+ type => 'boolean',
+ description => "Indicates if qemu shutdown cleanly.",
+ },
+ 'guest-requested' => {
+ type => 'boolean',
+ description => "Indicates if the shutdown was requested by the guest or via qmp.",
+ },
+ },
+ },
+ returns => { type => 'null', },
+ code => sub {
+ my ($param) = @_;
+
+ my $vmid = $param->{vmid};
+ my $clean = $param->{'clean-shutdown'};
+ my $guest = $param->{'guest-requested'};
+
+ # return if we do not have the config anymore
+ return if !-f PVE::QemuConfig->config_file($vmid);
+
+ my $storecfg = PVE::Storage::config();
+ warn "Starting cleanup for $vmid\n";
+
+ PVE::QemuConfig->lock_config($vmid, sub {
+ my $conf = PVE::QemuConfig->load_config ($vmid);
+ my $pid = PVE::QemuServer::check_running ($vmid);
+ die "vm still running\n" if $pid;
+
+ if (!$clean) {
+ # we have to cleanup the tap devices after a crash
+
+ foreach my $opt (keys %$conf) {
+ next if $opt !~ m/^net(\d)+$/;
+ my $interface = $1;
+ PVE::Network::tap_unplug("tap${vmid}i${interface}");
+ }
+ }
+
+ if (!$clean || $guest) {
+ # vm was shutdown from inside the guest or crashed, doing api cleanup
+ PVE::QemuServer::vm_stop_cleanup($storecfg, $vmid, $conf, 0, 0);
+ }
+ });
+
+ warn "Finished cleanup for $vmid\n";
+
+ return undef;
+ }});
+
my $print_agent_result = sub {
my ($data) = @_;
- my $result = $data->{result};
+ my $result = $data->{result} // $data;
return if !defined($result);
my $class = ref($result);
print to_json($result, { pretty => 1, canonical => 1});
};
+sub param_mapping {
+ my ($name) = @_;
+
+ my $ssh_key_map = ['sshkeys', sub {
+ return URI::Escape::uri_escape(PVE::Tools::file_get_contents($_[0]));
+ }];
+ my $cipassword_map = PVE::CLIHandler::get_standard_mapping('pve-password', { name => 'cipassword' });
+ my $password_map = PVE::CLIHandler::get_standard_mapping('pve-password');
+ my $mapping = {
+ 'update_vm' => [$ssh_key_map, $cipassword_map],
+ 'create_vm' => [$ssh_key_map, $cipassword_map],
+ 'set-user-password' => [$password_map],
+ };
+
+ return $mapping->{$name};
+}
+
our $cmddef = {
list => [ "PVE::API2::Qemu", 'vmlist', [],
{ node => $nodename }, sub {
monitor => [ __PACKAGE__, 'monitor', ['vmid']],
- agent => [ "PVE::API2::Qemu", 'agent', ['vmid', 'command'],
- { node => $nodename }, $print_agent_result ],
+ agent => { alias => 'guest cmd' },
+
+ guest => {
+ cmd => [ "PVE::API2::Qemu::Agent", 'agent', ['vmid', 'command'], { node => $nodename }, $print_agent_result ],
+ passwd => [ "PVE::API2::Qemu::Agent", 'set-user-password', [ 'vmid', 'username' ], { node => $nodename }],
+ exec => [ __PACKAGE__, 'exec', [ 'vmid', 'extra-args' ], { node => $nodename }, $print_agent_result],
+ 'exec-status' => [ "PVE::API2::Qemu::Agent", 'exec-status', [ 'vmid', 'pid' ], { node => $nodename }, $print_agent_result],
+ },
mtunnel => [ __PACKAGE__, 'mtunnel', []],
importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
+ cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
+
};
1;