]> git.proxmox.com Git - qemu-server.git/blobdiff - PVE/CLI/qm.pm
qm showcmd --pretty: indent new lines by 2 spaces
[qemu-server.git] / PVE / CLI / qm.pm
index 9a8f83954d1ac8e4a5a670b8728d7d793bbf5b2f..564e443951bf9c5356ed4cf37195e6464036e039 100755 (executable)
@@ -17,7 +17,10 @@ use PVE::SafeSyslog;
 use PVE::INotify;
 use PVE::RPCEnvironment;
 use PVE::QemuServer;
+use PVE::QemuServer::ImportDisk;
+use PVE::QemuServer::OVF;
 use PVE::API2::Qemu;
+use JSON;
 use PVE::JSONSchema qw(get_standard_option);
 use Term::ReadLine;
 
@@ -33,6 +36,10 @@ my $upid_exit = sub {
 
 my $nodename = PVE::INotify::nodename();
 
+sub setup_environment {
+    PVE::RPCEnvironment->setup_default_cli_env();
+}
+
 sub run_vnc_proxy {
     my ($path) = @_;
 
@@ -75,6 +82,32 @@ sub run_vnc_proxy {
     exit(0);
 }
 
+sub print_recursive_hash {
+    my ($prefix, $hash, $key) = @_;
+
+    if (ref($hash) eq 'HASH') {
+       if (defined($key)) {
+           print "$prefix$key:\n";
+       }
+       foreach my $itemkey (keys %$hash) {
+           print_recursive_hash("\t$prefix", $hash->{$itemkey}, $itemkey);
+       }
+    } elsif (ref($hash) eq 'ARRAY') {
+       if (defined($key)) {
+           print "$prefix$key:\n";
+       }
+       foreach my $item (@$hash) {
+           print_recursive_hash("\t$prefix", $item);
+       }
+    } elsif (!ref($hash) && defined($hash)) {
+       if (defined($key)) {
+           print "$prefix$key: $hash\n";
+       } else {
+           print "$prefix$hash\n";
+       }
+    }
+}
+
 __PACKAGE__->register_method ({
     name => 'showcmd',
     path => 'showcmd',
@@ -84,6 +117,12 @@ __PACKAGE__->register_method ({
        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,
+           }
        },
     },
     returns => { type => 'null'},
@@ -91,7 +130,11 @@ __PACKAGE__->register_method ({
        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});
+
+       $cmdline =~ s/ -/ \\\n  -/g if $param->{pretty};
+
+       print "$cmdline\n";
 
        return undef;
     }});
@@ -117,19 +160,18 @@ __PACKAGE__->register_method ({
        my ($param) = @_;
 
        # test if VM exists
-       my $conf = PVE::QemuServer::load_config ($param->{vmid});
+       my $conf = PVE::QemuConfig->load_config ($param->{vmid});
 
-       my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid});
+       my $vmstatus = PVE::QemuServer::vmstatus($param->{vmid}, 1);
        my $stat = $vmstatus->{$param->{vmid}};
        if ($param->{verbose}) {
            foreach my $k (sort (keys %$stat)) {
                next if $k eq 'cpu' || $k eq 'relcpu'; # always 0
                my $v = $stat->{$k};
-               next if !defined($v);
-               print "$k: $v\n";
+               print_recursive_hash("", $v, $k);
            }
        } else {
-           my $status = $stat->{status} || 'unknown';
+           my $status = $stat->{qmpstatus} || 'unknown';
            print "status: $status\n";
        }
 
@@ -184,16 +226,38 @@ __PACKAGE__->register_method ({
 
        my $vmid = $param->{vmid};
 
-       PVE::QemuServer::lock_config ($vmid, sub {
-           my $conf = PVE::QemuServer::load_config($vmid);
+       PVE::QemuConfig->lock_config ($vmid, sub {
+           my $conf = PVE::QemuConfig->load_config($vmid);
            delete $conf->{lock};
            delete $conf->{pending}->{lock} if $conf->{pending}; # just to be sure
-           PVE::QemuServer::write_config($vmid, $conf, 1);
+           PVE::QemuConfig->write_config($vmid, $conf);
        });
 
        return undef;
     }});
 
+__PACKAGE__->register_method ({
+    name => 'nbdstop',
+    path => 'nbdstop',
+    method => 'PUT',
+    description => "Stop embedded nbd server.",
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::QemuServer::complete_vmid }),
+       },
+    },
+    returns => { type => 'null'},
+    code => sub {
+       my ($param) = @_;
+
+       my $vmid = $param->{vmid};
+
+       PVE::QemuServer::nbd_stop($vmid);
+
+       return undef;
+    }});
+
 __PACKAGE__->register_method ({
     name => 'mtunnel',
     path => 'mtunnel',
@@ -212,12 +276,34 @@ __PACKAGE__->register_method ({
            return undef;
        }
 
-       print "tunnel online\n";
-       *STDOUT->flush();
+       my $tunnel_write = sub {
+           my $text = shift;
+           chomp $text;
+           print "$text\n";
+           *STDOUT->flush();
+       };
+
+       $tunnel_write->("tunnel online");
+       $tunnel_write->("ver 1");
 
        while (my $line = <>) {
            chomp $line;
-           last if $line =~ m/^quit$/;
+           if ($line =~ /^quit$/) {
+               $tunnel_write->("OK");
+               last;
+           } elsif ($line =~ /^resume (\d+)$/) {
+               my $vmid = $1;
+               if (PVE::QemuServer::check_running($vmid, 1)) {
+                   eval { PVE::QemuServer::vm_resume($vmid, 1, 1); };
+                   if ($@) {
+                       $tunnel_write->("ERR: resume failed - $@");
+                   } else {
+                       $tunnel_write->("OK");
+                   }
+               } else {
+                   $tunnel_write->("ERR: resume failed - VM $vmid not running");
+               }
+           }
        }
 
        return undef;
@@ -280,7 +366,7 @@ __PACKAGE__->register_method ({
 
        my $vmid = $param->{vmid};
 
-       my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
+       my $conf = PVE::QemuConfig->load_config ($vmid); # check if VM exists
 
        print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
 
@@ -327,6 +413,60 @@ __PACKAGE__->register_method ({
        return undef;
     }});
 
+__PACKAGE__->register_method ({
+    name => 'importdisk',
+    path => 'importdisk',
+    method => 'POST',
+    description => "Import an external disk image as an unused disk in a VM. The
+ image format has to be supported by qemu-img(1).",
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           vmid => get_standard_option('pve-vmid', {completion => \&PVE::QemuServer::complete_vmid}),
+           source => {
+               description => 'Path to the disk image to import',
+               type => 'string',
+               optional => 0,
+           },
+            storage => get_standard_option('pve-storage-id', {
+               description => 'Target storage ID',
+               completion => \&PVE::QemuServer::complete_storage,
+               optional => 0,
+            }),
+           format => {
+               type => 'string',
+               description => 'Target format',
+               enum => [ 'raw', 'qcow2', 'vmdk' ],
+               optional => 1,
+           },
+       },
+    },
+    returns => { type => 'null'},
+    code => sub {
+       my ($param) = @_;
+
+       my $vmid = extract_param($param, 'vmid');
+       my $source = extract_param($param, 'source');
+       my $storeid = extract_param($param, 'storage');
+       my $format = extract_param($param, 'format');
+
+       my $vm_conf = PVE::QemuConfig->load_config($vmid);
+       PVE::QemuConfig->check_lock($vm_conf);
+       die "$source: non-existent or non-regular file\n" if (! -f $source);
+
+       my $storecfg = PVE::Storage::config();
+       PVE::Storage::storage_check_enabled($storecfg, $storeid);
+
+       my $target_storage_config =
+           PVE::Storage::storage_config($storecfg, $storeid);
+       die "storage $storeid does not support vm images\n"
+           if !$target_storage_config->{content}->{images};
+
+       PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
+
+       return undef;
+    }});
+
 __PACKAGE__->register_method ({
     name => 'terminal',
     path => 'terminal',
@@ -341,7 +481,13 @@ __PACKAGE__->register_method ({
                type => 'string',
                optional => 1,
                enum => [qw(serial0 serial1 serial2 serial3)],
-           }
+           },
+           escape => {
+               description => "Escape character.",
+               type => 'string',
+               optional => 1,
+               default => '^O',
+           },
        },
     },
     returns => { type => 'null'},
@@ -350,7 +496,25 @@ __PACKAGE__->register_method ({
 
        my $vmid = $param->{vmid};
 
-       my $conf = PVE::QemuServer::load_config ($vmid); # check if VM exists
+       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};
 
@@ -371,15 +535,133 @@ __PACKAGE__->register_method ({
 
        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);
 
        return undef;
     }});
 
+__PACKAGE__->register_method ({
+    name => 'importovf',
+    path => 'importovf',
+    description => "Create a new VM using parameters read from an OVF manifest",
+    parameters => {
+       additionalProperties => 0,
+       properties => {
+           vmid => get_standard_option('pve-vmid', { completion => \&PVE::Cluster::complete_next_vmid }),
+           manifest => {
+               type => 'string',
+               description => 'path to the ovf file',
+               },
+           storage => get_standard_option('pve-storage-id', {
+               description => 'Target storage ID',
+               completion => \&PVE::QemuServer::complete_storage,
+               optional => 0,
+           }),
+           format => {
+               type => 'string',
+               description => 'Target format',
+               enum => [ 'raw', 'qcow2', 'vmdk' ],
+               optional => 1,
+           },
+           dryrun => {
+               type => 'boolean',
+               description => 'Print a parsed representation of the extracted OVF parameters, but do not create a VM',
+               optional => 1,
+           }
+       },
+    },
+    returns => { type => 'null' },
+    code => sub {
+       my ($param) = @_;
+
+       my $vmid = PVE::Tools::extract_param($param, 'vmid');
+       my $ovf_file = PVE::Tools::extract_param($param, 'manifest');
+       my $storeid = PVE::Tools::extract_param($param, 'storage');
+       my $format = PVE::Tools::extract_param($param, 'format');
+       my $dryrun = PVE::Tools::extract_param($param, 'dryrun');
+
+       die "$ovf_file: non-existent or non-regular file\n" if (! -f $ovf_file);
+       my $storecfg = PVE::Storage::config();
+       PVE::Storage::storage_check_enabled($storecfg, $storeid);
+
+       my $parsed = PVE::QemuServer::OVF::parse_ovf($ovf_file);
+
+       if ($dryrun) {
+           print to_json($parsed, { pretty => 1, canonical => 1});
+           return;
+       }
+
+       $param->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
+       $param->{memory} = $parsed->{qm}->{memory} if defined($parsed->{qm}->{memory});
+       $param->{cores} = $parsed->{qm}->{cores} if defined($parsed->{qm}->{cores});
+
+       my $importfn = sub {
+
+           PVE::Cluster::check_vmid_unused($vmid);
+
+           my $conf = $param;
+
+           eval {
+               # order matters, as do_import() will load_config() internally
+               $conf->{smbios1} = PVE::QemuServer::generate_smbios1_uuid();
+               PVE::QemuConfig->write_config($vmid, $conf);
+
+               foreach my $disk (@{ $parsed->{disks} }) {
+                   my ($file, $drive) = ($disk->{backing_file}, $disk->{disk_address});
+                   PVE::QemuServer::ImportDisk::do_import($file, $vmid, $storeid,
+                       { drive_name => $drive, format => $format });
+               }
+
+               # reload after disks entries have been created
+               $conf = PVE::QemuConfig->load_config($vmid);
+               PVE::QemuConfig->check_lock($conf);
+               my $firstdisk = PVE::QemuServer::resolve_first_disk($conf);
+               $conf->{bootdisk} = $firstdisk if $firstdisk;
+               PVE::QemuConfig->write_config($vmid, $conf);
+           };
+
+           my $err = $@;
+           if ($err) {
+               my $skiplock = 1;
+               eval { PVE::QemuServer::vm_destroy($storecfg, $vmid, $skiplock); };
+               die "import failed - $err";
+           }
+       };
+
+       my $wait_for_lock = 1;
+       PVE::QemuConfig->lock_config_full($vmid, $wait_for_lock, $importfn);
+
+       return undef;
+
+    }
+});
+
+my $print_agent_result = sub {
+    my ($data) = @_;
+
+    my $result = $data->{result};
+    return if !defined($result);
+
+    my $class = ref($result);
+
+    if (!$class) {
+       chomp $result;
+       return if $result =~ m/^\s*$/;
+       print "$result\n";
+       return;
+    }
+
+    if (($class eq 'HASH') && !scalar(keys %$result)) { # empty hash
+       return;
+    }
+
+    print to_json($result, { pretty => 1, canonical => 1});
+};
+
 our $cmddef = {
     list => [ "PVE::API2::Qemu", 'vmlist', [],
             { node => $nodename }, sub {
@@ -392,7 +674,7 @@ our $cmddef = {
 
                 foreach my $rec (sort { $a->{vmid} <=> $b->{vmid} } @$vmlist) {
                     printf "%10s %-20s %-10s %-10s %12.2f %-10s\n", $rec->{vmid}, $rec->{name},
-                    $rec->{status},
+                    $rec->{qmpstatus} || $rec->{status},
                     ($rec->{maxmem} || 0)/(1024*1024),
                     ($rec->{maxdisk} || 0)/(1024*1024*1024),
                     $rec->{pid}||0;
@@ -465,6 +747,17 @@ our $cmddef = {
 
     delsnapshot => [ "PVE::API2::Qemu", 'delsnapshot', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
 
+    listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename },
+                   sub {
+                       my $res = shift;
+                       foreach my $e (@$res) {
+                           my $headline = $e->{description} || 'no-description';
+                           $headline =~ s/\n.*//sg;
+                           my $parent = $e->{parent} // 'no-parent';
+                           printf("%-20s %-20s %s\n", $e->{name}, $parent, $headline);
+                       }
+                   }],
+
     rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
 
     template => [ "PVE::API2::Qemu", 'template', ['vmid'], { node => $nodename }],
@@ -493,65 +786,19 @@ our $cmddef = {
 
     monitor  => [ __PACKAGE__, 'monitor', ['vmid']],
 
-    mtunnel => [ __PACKAGE__, 'mtunnel', []],
-
-    terminal => [ __PACKAGE__, 'terminal', ['vmid']],
-};
-
-1;
-
-__END__
-
-=head1 NAME
+    agent  => [ "PVE::API2::Qemu", 'agent', ['vmid', 'command'],
+               { node => $nodename }, $print_agent_result ],
 
-qm - qemu/kvm virtual machine manager
-
-=head1 SYNOPSIS
-
-=include synopsis
-
-=head1 DESCRIPTION
-
-qm is a script to manage virtual machines with qemu/kvm. You can
-create and destroy virtual machines, and control execution
-(start/stop/suspend/resume). Besides that, you can use qm to set
-parameters in the associated config file. It is also possible to
-create and delete virtual disks.
-
-=head1 CONFIGURATION
-
-All configuration files consists of lines in the form
-
-       PARAMETER: value
-
-See L<vm.conf|vm.conf> for a complete list of options.
-
-Configuration files are stored inside the Proxmox configuration file system, and can be access at F</etc/pve/qemu-server/C<VMID>.conf>.
-
-The default for option 'keyboard' is read from
-F</etc/pve/datacenter.conf>.
-
-=head1 Locks
-
-Online migration and backups (vzdump) set a lock to prevent
-unintentional action on such VMs. Sometimes you need remove such lock
-manually (power failure).
-
- qm unlock <vmid>
-
-=head1 EXAMPLES
+    mtunnel => [ __PACKAGE__, 'mtunnel', []],
 
- # create a new VM with 4 GB ide disk
- qm create 300 -ide0 4 -net0 e1000 -cdrom proxmox-mailgateway_2.1.iso
+    nbdstop => [ __PACKAGE__, 'nbdstop', ['vmid']],
 
- # start the new VM
- qm start 300
+    terminal => [ __PACKAGE__, 'terminal', ['vmid']],
 
- # send shutdown, then wait until VM is stopped
- qm shutdown 300 && qm wait 300
+    importdisk => [ __PACKAGE__, 'importdisk', ['vmid', 'source', 'storage']],
 
- # same as above, but only wait for 40 seconds
- qm shutdown 300 && qm wait 300 -timeout 40
+    importovf => [ __PACKAGE__, 'importovf', ['vmid', 'manifest', 'storage']],
 
+};
 
-=include pve_copyright
+1;