]> git.proxmox.com Git - qemu-server.git/blobdiff - PVE/CLI/qm.pm
qm status: sort hash keys on verbose output
[qemu-server.git] / PVE / CLI / qm.pm
index 279d0d96860ef8ba4925a3b25e2c50cb08065fc1..f8972bd325f7e7004cb91d4b7b099a8465f0f7e2 100755 (executable)
@@ -8,31 +8,35 @@ use Getopt::Long qw(:config no_getopt_compat);
 
 use Fcntl ':flock';
 use File::Path;
-use IO::Socket::UNIX;
 use IO::Select;
-use URI::Escape;
+use IO::Socket::UNIX;
+use JSON;
 use POSIX qw(strftime);
+use Term::ReadLine;
+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::GuestHelpers;
-use PVE::QemuServer;
+use PVE::INotify;
+use PVE::JSONSchema qw(get_standard_option);
+use PVE::Network;
+use PVE::RPCEnvironment;
+use PVE::SafeSyslog;
+use PVE::Tools qw(extract_param);
+
+use PVE::API2::Qemu::Agent;
+use PVE::API2::Qemu;
+use PVE::QemuConfig;
+use PVE::QemuServer::Drive;
+use PVE::QemuServer::Helpers;
+use PVE::QemuServer::Agent qw(agent_available);
 use PVE::QemuServer::ImportDisk;
+use PVE::QemuServer::Monitor qw(mon_cmd);
 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 PVE::QemuServer;
 
 use PVE::CLIHandler;
-
 use base qw(PVE::CLIHandler);
 
 my $upid_exit = sub {
@@ -57,7 +61,7 @@ sub run_vnc_proxy {
 
     die "unable to connect to socket '$path' - $!" if !$s;
 
-    my $select = new IO::Select;
+    my $select = IO::Select->new();
 
     $select->add(\*STDIN);
     $select->add($s);
@@ -96,17 +100,17 @@ sub print_recursive_hash {
        if (defined($key)) {
            print "$prefix$key:\n";
        }
-       foreach my $itemkey (keys %$hash) {
+       for my $itemkey (sort 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) {
+       for my $item (@$hash) {
            print_recursive_hash("\t$prefix", $item);
        }
-    } elsif (!ref($hash) && defined($hash)) {
+    } elsif ((!ref($hash) && defined($hash)) || ref($hash) eq 'JSON::PP::Boolean') {
        if (defined($key)) {
            print "$prefix$key: $hash\n";
        } else {
@@ -151,7 +155,7 @@ __PACKAGE__->register_method ({
 
        print "$cmdline\n";
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -190,7 +194,7 @@ __PACKAGE__->register_method ({
            print "status: $status\n";
        }
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -209,19 +213,21 @@ __PACKAGE__->register_method ({
        my ($param) = @_;
 
        my $vmid = $param->{vmid};
-       my $vnc_socket = PVE::QemuServer::vnc_socket($vmid);
+       PVE::QemuConfig::assert_config_exists_on_node($vmid);
+       my $vnc_socket = PVE::QemuServer::Helpers::vnc_socket($vmid);
 
        if (my $ticket = $ENV{LC_PVE_TICKET}) {  # NOTE: ssh on debian only pass LC_* variables
-           PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
-           PVE::QemuServer::vm_mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
-           PVE::QemuServer::vm_mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
+           mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
+           mon_cmd($vmid, "set_password", protocol => 'vnc', password => $ticket);
+           mon_cmd($vmid, "expire_password", protocol => 'vnc', time => "+30");
        } else {
-           PVE::QemuServer::vm_mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,x509,password");
+           # FIXME: remove or allow to add tls-creds object, as x509 vnc param is removed with qemu 4??
+           mon_cmd($vmid, "change", device => 'vnc', target => "unix:$vnc_socket,password");
        }
 
        run_vnc_proxy($vnc_socket);
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -248,7 +254,7 @@ __PACKAGE__->register_method ({
            PVE::QemuConfig->write_config($vmid, $conf);
        });
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -268,9 +274,10 @@ __PACKAGE__->register_method ({
 
        my $vmid = $param->{vmid};
 
-       PVE::QemuServer::nbd_stop($vmid);
+       eval { PVE::QemuServer::nbd_stop($vmid) };
+       warn $@ if $@;
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -288,7 +295,7 @@ __PACKAGE__->register_method ({
 
        if (!PVE::Cluster::check_cfs_quorum(1)) {
            print "no quorum\n";
-           return undef;
+           return;
        }
 
        my $tunnel_write = sub {
@@ -321,7 +328,7 @@ __PACKAGE__->register_method ({
            }
        }
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -361,7 +368,7 @@ __PACKAGE__->register_method ({
 
        die "wait failed - got timeout\n" if PVE::QemuServer::check_running ($vmid);
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -385,23 +392,18 @@ __PACKAGE__->register_method ({
 
        print "Entering Qemu Monitor for VM $vmid - type 'help' for help\n";
 
-       my $term = new Term::ReadLine ('qm');
+       my $term = Term::ReadLine->new('qm');
 
-       my $input;
-       while (defined ($input = $term->readline('qm> '))) {
+       while (defined(my $input = $term->readline('qm> '))) {
            chomp $input;
-
            next if $input =~ m/^\s*$/;
-
            last if $input =~ m/^\s*q(uit)?\s*$/;
 
-           eval {
-               print PVE::QemuServer::vm_human_monitor_command ($vmid, $input);
-           };
+           eval { print PVE::QemuServer::Monitor::hmp_cmd($vmid, $input) };
            print "ERROR: $@" if $@;
        }
 
-       return undef;
+       return;
 
     }});
 
@@ -435,7 +437,7 @@ __PACKAGE__->register_method ({
 
        PVE::QemuServer::rescan($param->{vmid}, 0, $dryrun);
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -482,14 +484,15 @@ __PACKAGE__->register_method ({
        my $storecfg = PVE::Storage::config();
        PVE::Storage::storage_check_enabled($storecfg, $storeid);
 
-       my $target_storage_config =
-           PVE::Storage::storage_config($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 });
+       print "importing disk '$source' to VM $vmid ...\n";
+       my ($drive_id, $volid) = PVE::QemuServer::ImportDisk::do_import($source, $vmid, $storeid, { format => $format });
+       print "Successfully imported disk as '$drive_id:$volid'\n";
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -566,7 +569,7 @@ __PACKAGE__->register_method ({
 
        system($cmd);
 
-       return undef;
+       return;
     }});
 
 __PACKAGE__->register_method ({
@@ -620,48 +623,57 @@ __PACKAGE__->register_method ({
            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});
+       eval { PVE::QemuConfig->create_and_lock_config($vmid) };
+       die "Reserving empty config for OVF import to VM $vmid failed: $@" if $@;
 
-       my $importfn = sub {
+       my $conf = PVE::QemuConfig->load_config($vmid);
+       die "Internal error: Expected 'create' lock in config of VM $vmid!"
+           if !PVE::QemuConfig->has_lock($conf, "create");
 
-           PVE::Cluster::check_vmid_unused($vmid);
+       $conf->{name} = $parsed->{qm}->{name} if defined($parsed->{qm}->{name});
+       $conf->{memory} = $parsed->{qm}->{memory} if defined($parsed->{qm}->{memory});
+       $conf->{cores} = $parsed->{qm}->{cores} if defined($parsed->{qm}->{cores});
 
-           my $conf = $param;
+       my $imported_disks = [];
+       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);
 
-           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);
+           foreach my $disk (@{ $parsed->{disks} }) {
+               my ($file, $drive) = ($disk->{backing_file}, $disk->{disk_address});
+               my ($name, $volid) = PVE::QemuServer::ImportDisk::do_import($file, $vmid, $storeid, {
+                   drive_name => $drive,
+                   format => $format,
+                   skiplock => 1,
+               });
+               # for cleanup on (later) error
+               push @$imported_disks, $volid;
+           }
 
-               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);
+           my $devs = PVE::QemuServer::get_default_bootdevices($conf);
+           $conf->{boot} = PVE::QemuServer::print_bootorder($devs);
+           PVE::QemuConfig->write_config($vmid, $conf);
+       };
 
-               # 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";
+       if (my $err = $@) {
+           my $skiplock = 1;
+           warn "error during import, cleaning up created resources...\n";
+           for my $volid (@$imported_disks) {
+               eval { PVE::Storage::vdisk_free($storecfg, $volid) };
+               warn "cleanup of $volid failed: $@\n" if $@;
            }
-       };
+           eval { PVE::QemuServer::destroy_vm($storecfg, $vmid, $skiplock) };
+           warn "Could not destroy VM $vmid: $@" if "$@";
+           die "import failed - $err";
+       }
 
-       my $wait_for_lock = 1;
-       PVE::QemuConfig->lock_config_full($vmid, $wait_for_lock, $importfn);
+       PVE::QemuConfig->remove_lock($vmid, "create");
 
-       return undef;
+       return;
 
     }
 });
@@ -691,6 +703,12 @@ __PACKAGE__->register_method({
                optional => 1,
                default => 30,
            },
+           'pass-stdin' => {
+               type => 'boolean',
+               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.",
+               optional => 1,
+               default => 0,
+           },
            'extra-args' => get_standard_option('extra-args'),
        },
     },
@@ -702,14 +720,28 @@ __PACKAGE__->register_method({
 
        my $vmid = $param->{vmid};
        my $sync = $param->{synchronous} // 1;
-       if (!$param->{'extra-args'} || !@{$param->{'extra-args'}}) {
-           raise_param_exc( { 'extra-args' => "No command given" });
-       }
+       my $pass_stdin = $param->{'pass-stdin'};
        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'});
+       my $input_data = undef;
+       if ($pass_stdin) {
+           $input_data = '';
+           while (my $line = <STDIN>) {
+               $input_data .= $line;
+               if (length($input_data) > 1024*1024) {
+                   # not sure how QEMU handles large amounts of data being
+                   # passed into the QMP socket, so limit to be safe
+                   die "'input-data' (STDIN) is limited to 1 MiB, aborting\n";
+               }
+           }
+       }
+
+       my $args = $param->{'extra-args'};
+       $args = undef if !$args || !@$args;
+
+       my $res = PVE::QemuServer::Agent::qemu_exec($vmid, $input_data, $args);
 
        if ($sync) {
            my $pid = $res->{pid};
@@ -762,6 +794,7 @@ __PACKAGE__->register_method({
        my $vmid = $param->{vmid};
        my $clean = $param->{'clean-shutdown'};
        my $guest = $param->{'guest-requested'};
+       my $restart = 0;
 
        # return if we do not have the config anymore
        return if !-f PVE::QemuConfig->config_file($vmid);
@@ -789,11 +822,22 @@ __PACKAGE__->register_method({
                PVE::QemuServer::vm_stop_cleanup($storecfg, $vmid, $conf, 0, 0);
            }
            PVE::GuestHelpers::exec_hookscript($conf, $vmid, 'post-stop');
+
+           $restart = eval { PVE::QemuServer::clear_reboot_request($vmid) };
+           warn $@ if $@;
        });
 
        warn "Finished cleanup for $vmid\n";
 
-       return undef;
+       if ($restart) {
+           warn "Restarting VM $vmid\n";
+           PVE::API2::Qemu->vm_start({
+               vmid => $vmid,
+               node => $nodename,
+           });
+       }
+
+       return;
     }});
 
 my $print_agent_result = sub {
@@ -885,33 +929,7 @@ our $cmddef = {
                    }
                }],
 
-    pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'],
-               { node => $nodename }, sub {
-                   my $data = shift;
-                   foreach my $item (sort { $a->{key} cmp $b->{key}} @$data) {
-                       my $k = $item->{key};
-                       next if $k eq 'digest';
-                       my $v = $item->{value};
-                       my $p = $item->{pending};
-                       if ($k eq 'description') {
-                           $v = PVE::Tools::encode_text($v) if defined($v);
-                           $p = PVE::Tools::encode_text($p) if defined($p);
-                       }
-                       if (defined($v)) {
-                           if ($item->{delete}) {
-                               print "del $k: $v\n";
-                           } elsif (defined($p)) {
-                               print "cur $k: $v\n";
-                               print "new $k: $p\n";
-                           } else {
-                               print "cur $k: $v\n";
-                           }
-                       } elsif (defined($p)) {
-                           print "new $k: $p\n";
-                       }
-                   }
-               }],
-
+    pending => [ "PVE::API2::Qemu", 'vm_pending', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::format_pending ],
     showcmd => [ __PACKAGE__, 'showcmd', ['vmid']],
 
     status => [ __PACKAGE__, 'status', ['vmid']],
@@ -920,59 +938,7 @@ 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;
-
-                       # "our" scope for the snaptimesort function
-                       my $snapshots = { map { $_->{name} => $_ } @$res };
-
-                       my $root;
-                       foreach my $e (@$res) {
-                           if (my $parent = $e->{parent}) {
-                               push @{$snapshots->{$parent}->{children}}, $e->{name};
-                           } else {
-                               $root = $e->{name};
-                           }
-                       }
-
-                       my $prefix = '`->';
-
-                       # sort the elements by snaptime - with "current" (no snaptime) highest
-                       my $snaptimesort = sub {
-                           return +1 if !defined $snapshots->{$a}->{snaptime};
-                           return -1 if !defined $snapshots->{$b}->{snaptime};
-                           return $snapshots->{$a}->{snaptime} <=> $snapshots->{$b}->{snaptime};
-                       };
-
-                       # recursion function for displaying the tree
-                       my $snapshottree;
-                       $snapshottree = sub {
-                           my ($prefix, $root, $snapshots) = @_;
-                           my $e = $snapshots->{$root};
-
-                           my $description = $e->{description} || 'no-description';
-                           ($description) = $description =~ m/(.*)$/m;
-
-                           # create the timestamp string
-                           my $timestring = "";
-                           if (defined $e->{snaptime}) {
-                               $timestring = strftime("%F %H:%M:%S", localtime($e->{snaptime}));
-                           }
-
-                           # for aligning the description
-                           my $len = 30 - length($prefix);
-                           printf("%s %-${len}s %-23s %s\n", $prefix, $root, $timestring, $description);
-                           if ($e->{children}) {
-                               $prefix = "    $prefix";
-                               foreach my $child (sort $snaptimesort @{$e->{children}}) {
-                                   $snapshottree->($prefix, $child, $snapshots);
-                               }
-                           }
-                       };
-
-                       $snapshottree->($prefix, $root, $snapshots);
-                   }],
+    listsnapshot => [ "PVE::API2::Qemu", 'snapshot_list', ['vmid'], { node => $nodename }, \&PVE::GuestHelpers::print_snapshot_tree],
 
     rollback => [ "PVE::API2::Qemu", 'rollback', ['vmid', 'snapname'], { node => $nodename } , $upid_exit ],
 
@@ -986,6 +952,8 @@ our $cmddef = {
 
     shutdown => [ "PVE::API2::Qemu", 'vm_shutdown', ['vmid'], { node => $nodename }, $upid_exit ],
 
+    reboot => [ "PVE::API2::Qemu", 'vm_reboot', ['vmid'], { node => $nodename }, $upid_exit ],
+
     suspend => [ "PVE::API2::Qemu", 'vm_suspend', ['vmid'], { node => $nodename }, $upid_exit ],
 
     resume => [ "PVE::API2::Qemu", 'vm_resume', ['vmid'], { node => $nodename }, $upid_exit ],
@@ -1023,6 +991,13 @@ our $cmddef = {
 
     cleanup => [ __PACKAGE__, 'cleanup', ['vmid', 'clean-shutdown', 'guest-requested'], { node => $nodename }],
 
+    cloudinit => {
+       dump => [ "PVE::API2::Qemu", 'cloudinit_generated_config_dump', ['vmid', 'type'], { node => $nodename }, sub {
+               my $data = shift;
+               print "$data\n";
+           }],
+    },
+
 };
 
 1;