Skip to contentSkip to conversation

qmp-shell non-interactive mode, delete scripts/qmp/qmp

PATCH Superseded Eduardo Habkost 5 participants 17 messages Aug 4, 2017 – Aug 8, 2017

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#7 lore raw

PATCH 3/5 qmp-shell: execute_cmdargs() method

In reply to Eduardo Habkost

This will allow us to execute a command that was already split in a list.

---
 scripts/qmp/qmp-shell | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
scripts/qmp/qmp-shell +6 -1
index 5fe6162..6113aaf 100755
@@ -260,7 +260,9 @@ class QMPShell(qmp.QEMUMonitorProtocol):
         print str(jsobj)
 
     def _execute_cmd(self, cmdline):
-        cmdargs = cmdline.split()
+        return self.execute_cmdargs(cmdline.split())
+
+    def execute_cmdargs(self, cmdargs):
         try:
             qmpcmd = self.__build_cmd(cmdargs)
         except Exception as e:
@@ -386,6 +388,9 @@ class HMPShell(QMPShell):
             print '%s: %s' % (resp['error']['class'], resp['error']['desc'])
         return True
 
+    def execute_cmdargs(self, cmdargs):
+        return self._execute_cmd(' '.join(cmdargs))
+
     def show_banner(self):
         QMPShell.show_banner(self, msg='Welcome to the HMP shell!')
 
Signature · 1 line
2.9.4
#9 lore raw

PATCH 4/5 qmp-shell: Accept QMP command as argument

In reply to Eduardo Habkost

This is useful for testing QMP commands in scripts.

Example usage, combined with 'jq' for filtering the results:

  $ ./scripts/qmp/qmp-shell /tmp/qmp qom-list path=/ | jq -r .return[].name
  machine
  type
  chardevs
  backend
  $
---
 scripts/qmp/qmp-shell | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
scripts/qmp/qmp-shell +10 -3
index 6113aaf..947fc36 100755
@@ -410,6 +410,10 @@ def main():
         default=True, help='Skip negotiate (for qemu-ga)')
     parser.add_argument('addr', metavar='ADDRESS',
         help='QMP socket address (Unix socket path or TCP address:port)')
+    parser.add_argument('cmd', metavar='COMMAND', nargs='?',
+        help='QMP command to be exeucted')
+    parser.add_argument('cmdargs', metavar='ARG=VALUE', nargs='*',
+        help='Argument to QMP command')
     args = parser.parse_args()
 
     try:
@@ -429,10 +433,13 @@ def main():
     except qemu.error:
         die('Could not connect to %s' % args.addr)
 
-    qemu.show_banner()
     qemu.set_verbosity(args.verbose)
-    while qemu.read_exec_command(qemu.get_prompt()):
-        pass
+    if args.cmd:
+        qemu.execute_cmdargs([args.cmd] + args.cmdargs)
+    else:
+        qemu.show_banner()
+        while qemu.read_exec_command(qemu.get_prompt()):
+            pass
     qemu.close()
 
 if __name__ == '__main__':
Signature · 1 line
2.9.4
#11 lore raw

PATCH 5/5 Remove scripts/qmp/qmp

In reply to Eduardo Habkost

The only purpose of scripts/qmp/qmp was the ability to run QMP commands non-interactively. Now it is possible to run qmp-shell non-interactively by providing a QMP command a command-line argument, making scripts/qmp/qmp obsolete.

---
 scripts/qmp/qmp | 126 --------------------------------------------------------
 1 file changed, 126 deletions(-)
 delete mode 100755 scripts/qmp/qmp
scripts/qmp/qmp deleted +0 -126
deleted file mode 100755
index 514b539..0000000
@@ -1,126 +0,0 @@
-#!/usr/bin/python
-#
-# QMP command line tool
-#
-# Copyright IBM, Corp. 2011
-#
-# Authors:
-#  Anthony Liguori <[email protected]>
-#
-# This work is licensed under the terms of the GNU GPLv2 or later.
-# See the COPYING file in the top-level directory.
-
-import sys, os
-from qmp import QEMUMonitorProtocol
-
-def print_response(rsp, prefix=[]):
-    if type(rsp) == list:
-        i = 0
-        for item in rsp:
-            if prefix == []:
-                prefix = ['item']
-            print_response(item, prefix[:-1] + ['%s[%d]' % (prefix[-1], i)])
-            i += 1
-    elif type(rsp) == dict:
-        for key in rsp.keys():
-            print_response(rsp[key], prefix + [key])
-    else:
-        if len(prefix):
-            print '%s: %s' % ('.'.join(prefix), rsp)
-        else:
-            print '%s' % (rsp)
-
-def main(args):
-    path = None
-
-    # Use QMP_PATH if it's set
-    if os.environ.has_key('QMP_PATH'):
-        path = os.environ['QMP_PATH']
-
-    while len(args):
-        arg = args[0]
-
-        if arg.startswith('--'):
-            arg = arg[2:]
-            if arg.find('=') == -1:
-                value = True
-            else:
-                arg, value = arg.split('=', 1)
-
-            if arg in ['path']:
-                if type(value) == str:
-                    path = value
-            elif arg in ['help']:
-                os.execlp('man', 'man', 'qmp')
-            else:
-                print 'Unknown argument "%s"' % arg
-
-            args = args[1:]
-        else:
-            break
-
-    if not path:
-        print "QMP path isn't set, use --path=qmp-monitor-address or set QMP_PATH"
-        return 1
-
-    if len(args):
-        command, args = args[0], args[1:]
-    else:
-        print 'No command found'
-        print 'Usage: "qmp [--path=qmp-monitor-address] qmp-cmd arguments"'
-        return 1
-
-    if command in ['help']:
-        os.execlp('man', 'man', 'qmp')
-
-    srv = QEMUMonitorProtocol(path)
-    srv.connect()
-
-    def do_command(srv, cmd, **kwds):
-        rsp = srv.cmd(cmd, kwds)
-        if rsp.has_key('error'):
-            raise Exception(rsp['error']['desc'])
-        return rsp['return']
-
-    commands = map(lambda x: x['name'], do_command(srv, 'query-commands'))
-
-    srv.close()
-
-    if command not in commands:
-        fullcmd = 'qmp-%s' % command
-        try:
-            os.environ['QMP_PATH'] = path
-            os.execvp(fullcmd, [fullcmd] + args)
-        except OSError as exc:
-            if exc.errno == 2:
-                print 'Command "%s" not found.' % (fullcmd)
-                return 1
-            raise
-        return 0
-
-    srv = QEMUMonitorProtocol(path)
-    srv.connect()
-
-    arguments = {}
-    for arg in args:
-        if not arg.startswith('--'):
-            print 'Unknown argument "%s"' % arg
-            return 1
-
-        arg = arg[2:]
-        if arg.find('=') == -1:
-            value = True
-        else:
-            arg, value = arg.split('=', 1)
-
-        if arg in ['help']:
-            os.execlp('man', 'man', 'qmp-%s' % command)
-            return 1
-
-        arguments[arg] = value
-
-    rsp = do_command(srv, command, **arguments)
-    print_response(rsp)
-
-if __name__ == '__main__':
-    sys.exit(main(sys.argv[1:]))
Signature · 1 line
2.9.4
#0 lore raw

cover qmp-shell non-interactive mode, delete scripts/qmp/qmp

This series adds the ability to run QMP commands non-interactively to qmp-shell, and deletes scripts/qmp/qmp.

Eduardo Habkost (5):
qmp-shell: Use argparse module
qmp-shell: Pass split cmdargs to __build_cmd()
qmp-shell: execute_cmdargs() method
qmp-shell: Accept QMP command as argument
Remove scripts/qmp/qmp

 scripts/qmp/qmp       | 126 --------------------------------------------------
 scripts/qmp/qmp-shell |  90 ++++++++++++++++--------------------
 2 files changed, 40 insertions(+), 176 deletions(-)
 delete mode 100755 scripts/qmp/qmp
Signature · 1 line
2.9.4
#1 lore raw

PATCH 1/5 qmp-shell: Use argparse module

It makes command-line parsing and generation of help text much simpler.

---
 scripts/qmp/qmp-shell | 61 +++++++++++++++++----------------------------------
 1 file changed, 20 insertions(+), 41 deletions(-)
scripts/qmp/qmp-shell +20 -41
index 860ffb2..c276b90 100755
@@ -73,6 +73,7 @@ import sys
 import os
 import errno
 import atexit
+import argparse
 
 class QMPCompleter(list):
     def complete(self, text, state):
@@ -393,61 +394,39 @@ def die(msg):
     sys.stderr.write('ERROR: %s\n' % msg)
     sys.exit(1)
 
-def fail_cmdline(option=None):
-    if option:
-        sys.stderr.write('ERROR: bad command-line option \'%s\'\n' % option)
-    sys.stderr.write('qmp-shell [ -v ] [ -p ] [ -H ] [ -N ] < UNIX socket path> | < TCP address:port >\n')
-    sys.stderr.write('    -v     Verbose (echo command sent and received)\n')
-    sys.stderr.write('    -p     Pretty-print JSON\n')
-    sys.stderr.write('    -H     Use HMP interface\n')
-    sys.stderr.write('    -N     Skip negotiate (for qemu-ga)\n')
-    sys.exit(1)
-
 def main():
-    addr = ''
-    qemu = None
-    hmp = False
-    pretty = False
-    verbose = False
-    negotiate = True
+    parser = argparse.ArgumentParser(description='QMP shell utility')
+    parser.add_argument('-v', action='store_true', dest='verbose',
+        help='Verbose (echo command sent and received)')
+    parser.add_argument('-p', action='store_true', dest='pretty',
+        help='Pretty-print JSON')
+    parser.add_argument('-H', action='store_true', dest='hmp',
+        help='Use HMP interface')
+    parser.add_argument('-N', action='store_false', dest='negotiate',
+        default=True, help='Skip negotiate (for qemu-ga)')
+    parser.add_argument('addr', metavar='ADDRESS',
+        help='QMP socket address (Unix socket path or TCP address:port)')
+    args = parser.parse_args()
 
     try:
-        for arg in sys.argv[1:]:
-            if arg == "-H":
-                if qemu is not None:
-                    fail_cmdline(arg)
-                hmp = True
-            elif arg == "-p":
-                pretty = True
-            elif arg == "-N":
-                negotiate = False
-            elif arg == "-v":
-                verbose = True
-            else:
-                if qemu is not None:
-                    fail_cmdline(arg)
-                if hmp:
-                    qemu = HMPShell(arg)
-                else:
-                    qemu = QMPShell(arg, pretty)
-                addr = arg
-
-        if qemu is None:
-            fail_cmdline()
+        if args.hmp:
+            qemu = HMPShell(args.addr)
+        else:
+            qemu = QMPShell(args.addr, args.pretty)
     except QMPShellBadPort:
         die('bad port number in command-line')
 
     try:
-        qemu.connect(negotiate)
+        qemu.connect(args.negotiate)
     except qmp.QMPConnectError:
         die('Didn\'t get QMP greeting message')
     except qmp.QMPCapabilitiesError:
         die('Could not negotiate capabilities')
     except qemu.error:
-        die('Could not connect to %s' % addr)
+        die('Could not connect to %s' % args.addr)
 
     qemu.show_banner()
-    qemu.set_verbosity(verbose)
+    qemu.set_verbosity(args.verbose)
     while qemu.read_exec_command(qemu.get_prompt()):
         pass
     qemu.close()
Signature · 1 line
2.9.4
#5 lore raw

PATCH 2/5 qmp-shell: Pass split cmdargs to __build_cmd()

In reply to Eduardo Habkost

This will allow us to implement a method to run a command that is already split in a list.

---
 scripts/qmp/qmp-shell | 9 ++++-----
 1 file changed, 4 insertions(+), 5 deletions(-)
scripts/qmp/qmp-shell +4 -5
index c276b90..5fe6162 100755
@@ -212,15 +212,13 @@ class QMPShell(qmp.QEMUMonitorProtocol):
                     raise QMPShellError('Cannot set "%s" multiple times' % key)
             parent[optpath[-1]] = value
 
-    def __build_cmd(self, cmdline):
+    def __build_cmd(self, cmdargs):
         """
         Build a QMP input object from a user provided command-line in the
         following format:
 
             < command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
         """
-        cmdargs = cmdline.split()
-
         # Transactional CLI entry/exit:
         if cmdargs[0] == 'transaction(':
             self._transmode = True
@@ -247,7 +245,7 @@ class QMPShell(qmp.QEMUMonitorProtocol):
                 finalize = True
             self.__cli_expr(cmdargs[1:], action['data'])
             self._actions.append(action)
-            return self.__build_cmd(')') if finalize else None
+            return self.__build_cmd([')']) if finalize else None
 
         # Standard command: parse and return it to be executed.
         qmpcmd = { 'execute': cmdargs[0], 'arguments': {} }
@@ -262,8 +260,9 @@ class QMPShell(qmp.QEMUMonitorProtocol):
         print str(jsobj)
 
     def _execute_cmd(self, cmdline):
+        cmdargs = cmdline.split()
         try:
-            qmpcmd = self.__build_cmd(cmdline)
+            qmpcmd = self.__build_cmd(cmdargs)
         except Exception as e:
             print 'Error while parsing command line: %s' % e
             print 'command format: <command-name> ',
Signature · 1 line
2.9.4
#13 lore raw
In reply to Eduardo Habkost
Quoted 2 lines · Eduardo Habkost

This series adds the ability to run QMP commands non-interactively to qmp-shell, and deletes scripts/qmp/qmp.

Hmm, not so simple:

$ git grep 'import qmp'
scripts/qemu.py:import qmp.qmp
scripts/qmp/qemu-ga-client:import qmp
scripts/qmp/qmp-shell:import qmp
scripts/qtest.py:import qmp.qmp
tests/migration/guestperf/engine.py:import qmp.qmp

Fam

#14 lore raw
Quoted 4 lines · Fam Zheng
Quoted 2 lines · Eduardo Habkost

This series adds the ability to run QMP commands non-interactively to qmp-shell, and deletes scripts/qmp/qmp.

Quoted 8 lines

Hmm, not so simple:

$ git grep 'import qmp'
scripts/qemu.py:import qmp.qmp
scripts/qmp/qemu-ga-client:import qmp
scripts/qmp/qmp-shell:import qmp
scripts/qtest.py:import qmp.qmp
tests/migration/guestperf/engine.py:import qmp.qmp

I'm deleting scripts/qmp/qmp, not scripts/qmp/qmp.py.

Signature · 1 line
Eduardo
#15 lore raw
Quoted 7 lines · Eduardo Habkost
Quoted 6 lines · Fam Zheng
Quoted 2 lines · Eduardo Habkost

This series adds the ability to run QMP commands non-interactively to qmp-shell, and deletes scripts/qmp/qmp.

Hmm, not so simple:

Quoted 8 lines
Quoted 6 lines
$ git grep 'import qmp'
scripts/qemu.py:import qmp.qmp
scripts/qmp/qemu-ga-client:import qmp
scripts/qmp/qmp-shell:import qmp
scripts/qtest.py:import qmp.qmp
tests/migration/guestperf/engine.py:import qmp.qmp

I'm deleting scripts/qmp/qmp, not scripts/qmp/qmp.py.

Yeah, OK, I was confused.

Fam

Tested-by Reviewed-by on the v1 series
#16 lore raw
In reply to Eduardo Habkost
Quoted 10 lines · Eduardo Habkost

This series adds the ability to run QMP commands non-interactively to qmp-shell, and deletes scripts/qmp/qmp.

Eduardo Habkost (5):
qmp-shell: Use argparse module
qmp-shell: Pass split cmdargs to __build_cmd()
qmp-shell: execute_cmdargs() method
qmp-shell: Accept QMP command as argument
Remove scripts/qmp/qmp

Quoted 5 lines
 scripts/qmp/qmp       | 126 --------------------------------------------------
 scripts/qmp/qmp-shell |  90 ++++++++++++++++--------------------
 2 files changed, 40 insertions(+), 176 deletions(-)
 delete mode 100755 scripts/qmp/qmp

Assuming there are no reasons to keep the old script around (I certainly never used it) this appears to be fine. May as well fortify one really good QMP tool instead of a dozen little half baked ones.

#2 lore raw

Re: [Qemu-devel] [PATCH for-2.11 1/5] qmp-shell: Use argparse module

In reply to Eduardo Habkost
Quoted 7 lines · Eduardo Habkost

It makes command-line parsing and generation of help text much simpler.

---
 scripts/qmp/qmp-shell | 61 +++++++++++++++++----------------------------------
 1 file changed, 20 insertions(+), 41 deletions(-)

The minimum Python version is 2.6. The argparse module was introduced in Python 2.7 so we cannot use it without increasing the minimum Python version:

https://docs.python.org/2.6/modindex.html

I suggest holding off on this for now.

Stefan

#3 lore raw

Re: [Qemu-devel] [PATCH for-2.11 1/5] qmp-shell: Use argparse module

In reply to Stefan Hajnoczi
Quoted 9 lines · Stefan Hajnoczi
Quoted 7 lines · Eduardo Habkost

It makes command-line parsing and generation of help text much simpler.

---
 scripts/qmp/qmp-shell | 61 +++++++++++++++++----------------------------------
 1 file changed, 20 insertions(+), 41 deletions(-)
Quoted 7 lines

The minimum Python version is 2.6. The argparse module was introduced in Python 2.7 so we cannot use it without increasing the minimum Python version:

https://docs.python.org/2.6/modindex.html

I suggest holding off on this for now.

Although its deprecated, perhaps we can use optparse instead ? It is available in py2 & 3 and very similar to argparse.

Regards,
Daniel

Signature · 3 lines
|: https://berrange.com      -o-    https://www.flickr.com/photos/dberrange :|
|: https://libvirt.org         -o-            https://fstop138.berrange.com :|
|: https://entangle-photo.org    -o-    https://www.instagram.com/dberrange :|
Reviewed-by on v1 4/5
#10 lore raw

Re: [Qemu-devel] [PATCH for-2.11 4/5] qmp-shell: Accept QMP command as argument

In reply to Eduardo Habkost
Quoted 11 lines · Eduardo Habkost

This is useful for testing QMP commands in scripts.

Example usage, combined with 'jq' for filtering the results:

  $ ./scripts/qmp/qmp-shell /tmp/qmp qom-list path=/ | jq -r .return[].name
  machine
  type
  chardevs
  backend
  $
Quoted 4 lines
---
 scripts/qmp/qmp-shell | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
Reviewed-by on v1 5/5
#12 lore raw

Re: [Qemu-devel] [PATCH for-2.11 5/5] Remove scripts/qmp/qmp

In reply to Eduardo Habkost
Quoted 10 lines · Eduardo Habkost

The only purpose of scripts/qmp/qmp was the ability to run QMP commands non-interactively. Now it is possible to run qmp-shell non-interactively by providing a QMP command a command-line argument, making scripts/qmp/qmp obsolete.

---
 scripts/qmp/qmp | 126 --------------------------------------------------------
 1 file changed, 126 deletions(-)
 delete mode 100755 scripts/qmp/qmp
#4 lore raw

Re: [Qemu-devel] [PATCH for-2.11 1/5] qmp-shell: Use argparse module

In reply to Stefan Hajnoczi
Quoted 9 lines · Stefan Hajnoczi
Quoted 7 lines · Eduardo Habkost

It makes command-line parsing and generation of help text much simpler.

---
 scripts/qmp/qmp-shell | 61 +++++++++++++++++----------------------------------
 1 file changed, 20 insertions(+), 41 deletions(-)
Quoted 7 lines

The minimum Python version is 2.6. The argparse module was introduced in Python 2.7 so we cannot use it without increasing the minimum Python version:

https://docs.python.org/2.6/modindex.html

I suggest holding off on this for now.

2.6 is the minimum Python version for what, exactly? Is it for building QEMU?

Note that qmp-shell is a tool for developers, not required for building or running QEMU. People who really want to run qmp-shell on a python-2.6 system can still install argparse if they want to use qmp-shell.

I could backport the code to optparse. But should we add code that relies on a deprecated module, if developers running Python 2.6 can install argparse?

Signature · 1 line
Eduardo