diff mbox series

[ovs-dev,v8,2/6] python: Add global option for JSON output to Python tools.

Message ID 20240411144718.1921869-3-jmeng@redhat.com
State Superseded, archived
Headers show
Series Add global option to output JSON from ovs-appctl cmds. | expand

Checks

Context Check Description
ovsrobot/apply-robot success apply and check: success
ovsrobot/github-robot-_Build_and_Test success github build: passed
ovsrobot/intel-ovs-compilation fail test: fail

Commit Message

Jakob Meng April 11, 2024, 2:47 p.m. UTC
From: Jakob Meng <code@jakobmeng.de>

This patch introduces support for different output formats to the
Python code, as did the previous commit for ovs-xxx tools like
'ovs-appctl --format json dpif/show'.
In particular, tests/appctl.py gains a global option '-f,--format'
which allows users to request JSON instead of plain-text for humans.

Reported-at: https://bugzilla.redhat.com/1824861
Signed-off-by: Jakob Meng <code@jakobmeng.de>
---
 NEWS                         |  2 ++
 python/ovs/unixctl/client.py | 14 ++++++++---
 python/ovs/unixctl/server.py | 45 +++++++++++++++++++++++++++++++++---
 python/ovs/util.py           |  8 +++++++
 tests/appctl.py              | 19 ++++++++++++++-
 tests/unixctl-py.at          |  3 +++
 6 files changed, 84 insertions(+), 7 deletions(-)
diff mbox series

Patch

diff --git a/NEWS b/NEWS
index 03ef6486b..f18238159 100644
--- a/NEWS
+++ b/NEWS
@@ -10,6 +10,8 @@  Post-v3.3.0
    - ovs-appctl:
      * Added new option [-f|--format] to choose the output format, e.g. 'json'
        or 'text' (by default).
+   - Python:
+     * Added support for choosing the output format, e.g. 'json' or 'text'.
 
 
 v3.3.0 - 16 Feb 2024
diff --git a/python/ovs/unixctl/client.py b/python/ovs/unixctl/client.py
index 8283f99bb..000d261c0 100644
--- a/python/ovs/unixctl/client.py
+++ b/python/ovs/unixctl/client.py
@@ -14,6 +14,7 @@ 
 
 import os
 
+import ovs.json
 import ovs.jsonrpc
 import ovs.stream
 import ovs.util
@@ -26,11 +27,12 @@  class UnixctlClient(object):
         assert isinstance(conn, ovs.jsonrpc.Connection)
         self._conn = conn
 
-    def transact(self, command, argv):
+    def transact(self, command, argv, fmt):
         assert isinstance(command, str)
         assert isinstance(argv, list)
         for arg in argv:
             assert isinstance(arg, str)
+        assert isinstance(fmt, ovs.util.OutputFormat)
 
         request = ovs.jsonrpc.Message.create_request(command, argv)
         error, reply = self._conn.transact_block(request)
@@ -40,11 +42,17 @@  class UnixctlClient(object):
                       % (self._conn.name, os.strerror(error)))
             return error, None, None
 
+        def to_string(body):
+            if fmt == ovs.util.OutputFormat.TEXT:
+                return str(body)
+            else:
+                return ovs.json.to_string(body)
+
         if reply.error is not None:
-            return 0, str(reply.error), None
+            return 0, to_string(reply.error), None
         else:
             assert reply.result is not None
-            return 0, None, str(reply.result)
+            return 0, None, to_string(reply.result)
 
     def close(self):
         self._conn.close()
diff --git a/python/ovs/unixctl/server.py b/python/ovs/unixctl/server.py
index b9cb52fad..f95317c4a 100644
--- a/python/ovs/unixctl/server.py
+++ b/python/ovs/unixctl/server.py
@@ -12,6 +12,7 @@ 
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+import argparse
 import copy
 import errno
 import os
@@ -35,6 +36,7 @@  class UnixctlConnection(object):
         assert isinstance(rpc, ovs.jsonrpc.Connection)
         self._rpc = rpc
         self._request_id = None
+        self._fmt = ovs.util.OutputFormat.TEXT
 
     def run(self):
         self._rpc.run()
@@ -65,9 +67,15 @@  class UnixctlConnection(object):
     def reply(self, body):
         self._reply_impl(True, body)
 
+    def reply_json(self, body):
+        self._reply_impl_json(True, body)
+
     def reply_error(self, body):
         self._reply_impl(False, body)
 
+    def reply_error_json(self, body):
+        self._reply_impl_json(False, body)
+
     # Called only by unixctl classes.
     def _close(self):
         self._rpc.close()
@@ -79,17 +87,27 @@  class UnixctlConnection(object):
             self._rpc.recv_wait(poller)
 
     def _reply_impl(self, success, body):
-        assert isinstance(success, bool)
         assert body is None or isinstance(body, str)
 
-        assert self._request_id is not None
-
         if body is None:
             body = ""
 
         if body and not body.endswith("\n"):
             body += "\n"
 
+        if self._fmt == ovs.util.OutputFormat.JSON:
+            body = {
+                "reply-format": "plain",
+                "reply": body
+            }
+
+        return self._reply_impl_json(success, body)
+
+    def _reply_impl_json(self, success, body):
+        assert isinstance(success, bool)
+
+        assert self._request_id is not None
+
         if success:
             reply = Message.create_reply(body, self._request_id)
         else:
@@ -136,6 +154,24 @@  def _unixctl_version(conn, unused_argv, version):
     conn.reply(version)
 
 
+def _unixctl_set_options(conn, argv, unused_aux):
+    assert isinstance(conn, UnixctlConnection)
+
+    parser = argparse.ArgumentParser()
+    parser.add_argument("--format", default="text",
+                        choices=[fmt.name.lower()
+                                 for fmt in ovs.util.OutputFormat])
+
+    try:
+        args = parser.parse_args(args=argv)
+    except argparse.ArgumentError as e:
+        conn.reply_error(str(e))
+        return
+
+    conn._fmt = ovs.util.OutputFormat[args.format.upper()]
+    conn.reply(None)
+
+
 class UnixctlServer(object):
     def __init__(self, listener):
         assert isinstance(listener, ovs.stream.PassiveStream)
@@ -210,4 +246,7 @@  class UnixctlServer(object):
         ovs.unixctl.command_register("version", "", 0, 0, _unixctl_version,
                                      version)
 
+        ovs.unixctl.command_register("set-options", "[--format text|json]", 2,
+                                     2, _unixctl_set_options, None)
+
         return 0, UnixctlServer(listener)
diff --git a/python/ovs/util.py b/python/ovs/util.py
index 3dba022f8..272ca683d 100644
--- a/python/ovs/util.py
+++ b/python/ovs/util.py
@@ -15,11 +15,19 @@ 
 import os
 import os.path
 import sys
+import enum
 
 PROGRAM_NAME = os.path.basename(sys.argv[0])
 EOF = -1
 
 
+@enum.unique
+# FIXME: Use @enum.verify(enum.NAMED_FLAGS) from Python 3.11 when available.
+class OutputFormat(enum.IntFlag):
+    TEXT = 1 << 0
+    JSON = 1 << 1
+
+
 def abs_file_name(dir_, file_name):
     """If 'file_name' starts with '/', returns a copy of 'file_name'.
     Otherwise, returns an absolute path to 'file_name' considering it relative
diff --git a/tests/appctl.py b/tests/appctl.py
index b85b364fa..7ccf34cc3 100644
--- a/tests/appctl.py
+++ b/tests/appctl.py
@@ -49,14 +49,31 @@  def main():
                         help="Arguments to the command.")
     parser.add_argument("-T", "--timeout", metavar="SECS",
                         help="wait at most SECS seconds for a response")
+    parser.add_argument("-f", "--format", metavar="FMT",
+                        help="Output format.", default="text",
+                        choices=[fmt.name.lower()
+                                 for fmt in ovs.util.OutputFormat])
     args = parser.parse_args()
 
     signal_alarm(int(args.timeout) if args.timeout else None)
 
     ovs.vlog.Vlog.init()
     target = args.target
+    format = ovs.util.OutputFormat[args.format.upper()]
     client = connect_to_target(target)
-    err_no, error, result = client.transact(args.command, args.argv)
+
+    if format != ovs.util.OutputFormat.TEXT:
+        err_no, error, _ = client.transact(
+            "set-options", ["--format", args.format], format)
+
+        if err_no:
+            ovs.util.ovs_fatal(err_no, "%s: transaction error" % target)
+        elif error is not None:
+            sys.stderr.write(error)
+            ovs.util.ovs_error(0, "%s: server returned an error" % target)
+            sys.exit(2)
+
+    err_no, error, result = client.transact(args.command, args.argv, format)
     client.close()
 
     if err_no:
diff --git a/tests/unixctl-py.at b/tests/unixctl-py.at
index 724006118..1440b30b7 100644
--- a/tests/unixctl-py.at
+++ b/tests/unixctl-py.at
@@ -100,6 +100,7 @@  The available commands are:
   exit
   help
   log                     [[arg ...]]
+  set-options             [[--format text|json]]
   version
   vlog/close
   vlog/list
@@ -112,6 +113,8 @@  AT_CHECK([PYAPPCTL_PY -t test-unixctl.py help], [0], [expout])
 AT_CHECK([ovs-vsctl --version | sed 's/ovs-vsctl/test-unixctl.py/' | head -1 > expout])
 AT_CHECK([APPCTL -t test-unixctl.py version], [0], [expout])
 AT_CHECK([PYAPPCTL_PY -t test-unixctl.py version], [0], [expout])
+AT_CHECK_UNQUOTED([PYAPPCTL_PY -t test-unixctl.py --format json version], [0], [dnl
+{"reply":"$(cat expout)\n","reply-format":"plain"}])
 
 AT_CHECK([APPCTL -t test-unixctl.py echo robot ninja], [0], [stdout])
 AT_CHECK([cat stdout | sed -e "s/u'/'/g"], [0], [dnl