qemu-devel.nongnu.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v4 0/7] AQMP TUI Draft
@ 2021-08-19 17:38 G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 1/7] python: disable pylint errors for aqmp-tui G S Niteesh Babu
                   ` (7 more replies)
  0 siblings, 8 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Hello all,

Gitlab: https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v4
CI: https://gitlab.com/niteesh.gs/qemu/-/pipelines/356024270

Revision since v3:
1) Added docstrings
2) Minor changes in AQMP TUI Draft
3) Switched to constant retry delay in QMP connection manager and other
   minor changes.

G S Niteesh Babu (7):
  python: disable pylint errors for aqmp-tui
  python: Add dependencies for AQMP TUI
  python/aqmp-tui: Add AQMP TUI draft
  python: Add entry point for aqmp-tui
  python: add optional pygments dependency
  python/aqmp-tui: Add syntax highlighting
  python/aqmp-tui: Add QMP connection manager

 python/Pipfile.lock          |  20 +
 python/qemu/aqmp/aqmp_tui.py | 681 +++++++++++++++++++++++++++++++++++
 python/setup.cfg             |  29 +-
 3 files changed, 729 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/aqmp_tui.py

-- 
2.17.1



^ permalink raw reply	[flat|nested] 15+ messages in thread

* [PATCH v4 1/7] python: disable pylint errors for aqmp-tui
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 2/7] python: Add dependencies for AQMP TUI G S Niteesh Babu
                   ` (6 subsequent siblings)
  7 siblings, 0 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Disable missing-docstring and fixme pylint warnings.
This is because since the AQMP is just a prototype
it is currently not documented properly and lot
of todo and fixme's are still in place.

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/setup.cfg | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/python/setup.cfg b/python/setup.cfg
index 077395f96e..e83c88db2c 100644
--- a/python/setup.cfg
+++ b/python/setup.cfg
@@ -90,6 +90,8 @@ ignore_missing_imports = True
 # --disable=W".
 disable=too-many-function-args,  # mypy handles this with less false positives.
         no-member,  # mypy also handles this better.
+        missing-docstring, # FIXME
+        fixme, # FIXME
 
 [pylint.basic]
 # Good variable names which should always be accepted, separated by a comma.
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v4 2/7] python: Add dependencies for AQMP TUI
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 1/7] python: disable pylint errors for aqmp-tui G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-21 19:54   ` John Snow
  2021-08-19 17:38 ` [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft G S Niteesh Babu
                   ` (5 subsequent siblings)
  7 siblings, 1 reply; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Added dependencies for the upcoming AQMP TUI under the optional
'tui' group.

The same dependencies have also been added under the devel group
since no work around has been found for optional groups to imply
other optional groups.

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/Pipfile.lock | 12 ++++++++++++
 python/setup.cfg    |  8 ++++++++
 2 files changed, 20 insertions(+)

diff --git a/python/Pipfile.lock b/python/Pipfile.lock
index 457f5c3fe8..da7a4ee164 100644
--- a/python/Pipfile.lock
+++ b/python/Pipfile.lock
@@ -289,6 +289,18 @@
             "markers": "python_version < '3.8'",
             "version": "==3.10.0.0"
         },
+        "urwid": {
+            "hashes": [
+                "sha256:588bee9c1cb208d0906a9f73c613d2bd32c3ed3702012f51efe318a3f2127eae"
+            ],
+            "version": "==2.1.2"
+        },
+        "urwid-readline": {
+            "hashes": [
+                "sha256:018020cbc864bb5ed87be17dc26b069eae2755cb29f3a9c569aac3bded1efaf4"
+            ],
+            "version": "==0.13"
+        },
         "virtualenv": {
             "hashes": [
                 "sha256:14fdf849f80dbb29a4eb6caa9875d476ee2a5cf76a5f5415fa2f1606010ab467",
diff --git a/python/setup.cfg b/python/setup.cfg
index e83c88db2c..a0ed3279d8 100644
--- a/python/setup.cfg
+++ b/python/setup.cfg
@@ -44,11 +44,18 @@ devel =
     mypy >= 0.770
     pylint >= 2.8.0
     tox >= 3.18.0
+    urwid >= 2.1.2
+    urwid-readline >= 0.13
 
 # Provides qom-fuse functionality
 fuse =
     fusepy >= 2.0.4
 
+# AQMP TUI dependencies
+tui =
+    urwid >= 2.1.2
+    urwid-readline >= 0.13
+
 [options.entry_points]
 console_scripts =
     qom = qemu.qmp.qom:main
@@ -133,5 +140,6 @@ allowlist_externals = make
 deps =
     .[devel]
     .[fuse]  # Workaround to trigger tox venv rebuild
+    .[tui]   # Workaround to trigger tox venv rebuild
 commands =
     make check
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 1/7] python: disable pylint errors for aqmp-tui G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 2/7] python: Add dependencies for AQMP TUI G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-21 20:05   ` John Snow
  2021-08-22  7:33   ` John Snow
  2021-08-19 17:38 ` [PATCH v4 4/7] python: Add entry point for aqmp-tui G S Niteesh Babu
                   ` (4 subsequent siblings)
  7 siblings, 2 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Added a draft of AQMP TUI.

Implements the follwing basic features:
1) Command transmission/reception.
2) Shows events asynchronously.
3) Shows server status in the bottom status bar.

Also added type annotations and necessary pylint,
mypy configurations

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/qemu/aqmp/aqmp_tui.py | 566 +++++++++++++++++++++++++++++++++++
 python/setup.cfg             |  15 +-
 2 files changed, 579 insertions(+), 2 deletions(-)
 create mode 100644 python/qemu/aqmp/aqmp_tui.py

diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
new file mode 100644
index 0000000000..12c9c4162a
--- /dev/null
+++ b/python/qemu/aqmp/aqmp_tui.py
@@ -0,0 +1,566 @@
+# Copyright (c) 2021
+#
+# Authors:
+#  Niteesh Babu G S <niteesh.gs@gmail.com>
+#
+# This work is licensed under the terms of the GNU GPL, version 2 or
+# later.  See the COPYING file in the top-level directory.
+"""
+AQMP TUI
+
+AQMP TUI is an asynchronous interface built on top the of the AQMP library.
+It is the successor of QMP-shell and is bought-in as a replacement for it.
+
+Example Usage: aqmp-tui <SOCKET | TCP IP:PORT>
+Full Usage: aqmp-tui --help
+"""
+
+import argparse
+import asyncio
+import logging
+from logging import Handler, LogRecord
+import signal
+from typing import (
+    List,
+    Optional,
+    Tuple,
+    Type,
+    Union,
+    cast,
+)
+
+import urwid
+import urwid_readline
+
+from ..qmp import QEMUMonitorProtocol, QMPBadPortError
+from .message import DeserializationError, Message, UnexpectedTypeError
+from .protocol import ConnectError
+from .qmp_client import ExecInterruptedError, QMPClient
+from .util import create_task, pretty_traceback
+
+
+# The name of the signal that is used to update the history list
+UPDATE_MSG: str = 'UPDATE_MSG'
+
+
+def format_json(msg: str) -> str:
+    """
+    Formats given multi-line JSON message into a single-line message.
+    Converting into single line is more asthetically pleasing when looking
+    along with error messages.
+
+    Eg:
+    Input:
+          [ 1,
+            true,
+            3 ]
+    The above input is not a valid QMP message and produces the following error
+    "QMP message is not a JSON object."
+    When displaying this in TUI in multiline mode we get
+
+        [ 1,
+          true,
+          3 ]: QMP message is not a JSON object.
+
+    whereas in singleline mode we get the following
+
+        [1, true, 3]: QMP message is not a JSON object.
+
+    The single line mode is more asthetically pleasing.
+
+    :param msg:
+        The message to formatted into single line.
+
+    :return: Formatted singleline message.
+
+    NOTE: We cannot use the JSON module here because it is only capable of
+    format valid JSON messages. But here the goal is to also format invalid
+    JSON messages.
+    """
+    msg = msg.replace('\n', '')
+    words = msg.split(' ')
+    words = [word for word in words if word != '']
+    return ' '.join(words)
+
+
+def has_tui_handler(logger: logging.Logger,
+                    handler_type: Type[Handler]) -> bool:
+    """
+    The Logger class has no interface to check if a certain type of handler is
+    installed or not. So we provide an interface to do so.
+
+    :param logger:
+        Logger object
+    :param handler_type:
+        The type of the handler to be checked.
+
+    :return: returns True if handler of type `handler_type` is installed else
+             False.
+    """
+    handlers = logger.handlers
+    for handler in handlers:
+        if isinstance(handler, handler_type):
+            return True
+    return False
+
+
+class App(QMPClient):
+    """
+    Implements the AQMP TUI.
+
+    Initializes the widgets and starts the urwid event loop.
+    """
+    def __init__(self, address: Union[str, Tuple[str, int]]) -> None:
+        """
+        Initializes the TUI.
+
+        :param address:
+            Address of the server to connect to.
+        """
+        urwid.register_signal(type(self), UPDATE_MSG)
+        self.window = Window(self)
+        self.address = address
+        self.aloop: Optional[asyncio.AbstractEventLoop] = None
+        super().__init__()
+
+    def add_to_history(self, msg: str, level: Optional[str] = None) -> None:
+        """
+        Appends the msg to the history list.
+
+        :param msg:
+            The raw message to be appended in string type.
+        """
+        urwid.emit_signal(self, UPDATE_MSG, msg, level)
+
+    def _cb_outbound(self, msg: Message) -> Message:
+        """
+        Callback: outbound message hook.
+
+        Appends the outgoing messages to the history box.
+
+        :param msg: raw outbound message.
+        :return: final outbound message.
+        """
+        str_msg = str(msg)
+
+        if not has_tui_handler(logging.getLogger(), TUILogHandler):
+            logging.debug('Request: %s', str_msg)
+        self.add_to_history('<-- ' + str_msg)
+        return msg
+
+    def _cb_inbound(self, msg: Message) -> Message:
+        """
+        Callback: outbound message hook.
+
+        Appends the incoming messages to the history box.
+
+        :param msg: raw inbound message.
+        :return: final inbound message.
+        """
+        str_msg = str(msg)
+
+        if not has_tui_handler(logging.getLogger(), TUILogHandler):
+            logging.debug('Request: %s', str_msg)
+        self.add_to_history('--> ' + str_msg)
+        return msg
+
+    def handle_event(self, event: Message) -> None:
+        """
+        Handles the event.
+
+        :param event:
+            The event to be handled.
+        """
+        # TODO: Consider all states present in qapi/run-state.json
+        if event['event'] == 'SHUTDOWN':
+            self._set_status('[Server Shutdown]')
+
+    async def wait_for_events(self) -> None:
+        """
+        This coroutine continously waits for events and dispatches them.
+        """
+        async for event in self.events:
+            self.handle_event(event)
+
+    async def _send_to_server(self, msg: Message) -> None:
+        """
+        This coroutine sends the message to the server.
+        The message has to be pre-validated.
+
+        :param msg:
+            Pre-validated message to be to sent to the server.
+
+        :raise Exception: When an unhandled exception is caught.
+        """
+        try:
+            await self._raw(msg, assign_id='id' not in msg)
+        except ExecInterruptedError:
+            logging.info('Error server disconnected before reply')
+            self.add_to_history('Server disconnected before reply', 'ERROR')
+            self._set_status("[Server Disconnected]")
+        except Exception as err:
+            logging.error('Exception from _send_to_server: %s', str(err))
+            raise err
+
+    def cb_send_to_server(self, raw_msg: str) -> None:
+        """
+        Validates and sends the message to the server.
+        The raw string message is first converted into a Message object
+        and is then sent to the server.
+
+        :param raw_msg:
+            The raw string message to be sent to the server.
+
+        :raise Exception: When an unhandled exception is caught.
+        """
+        try:
+            raw_msg = format_json(raw_msg)
+            msg = Message(bytes(raw_msg, encoding='utf-8'))
+            create_task(self._send_to_server(msg))
+        except (ValueError, TypeError) as err:
+            logging.info('Invalid message: %s', str(err))
+            self.add_to_history(f'{raw_msg}: {err}')
+        except (DeserializationError, UnexpectedTypeError) as err:
+            logging.info('Invalid message: %s', err.error_message)
+            self.add_to_history(f'{raw_msg}: {err.error_message}')
+
+    def unhandled_input(self, key: str) -> None:
+        """
+        Handle's keys which haven't been handled by the child widgets.
+
+        :param key:
+            Unhandled key
+        """
+        if key == 'esc':
+            self.kill_app()
+
+    def kill_app(self) -> None:
+        """
+        Initiates killing of app. A bridge between asynchronous and synchronous
+        code.
+        """
+        create_task(self._kill_app())
+
+    async def _kill_app(self) -> None:
+        """
+        This coroutine initiates the actual disconnect process and calls
+        urwid.ExitMainLoop() to kill the TUI.
+
+        :raise Exception: When an unhandled exception is caught.
+        """
+        # It is ok to call disconnect even in disconnect state
+        try:
+            await self.disconnect()
+            logging.debug('Disconnect finished. Exiting app')
+        except EOFError:
+            # We receive an EOF during disconnect, ignore that
+            pass
+        except Exception as err:
+            logging.info('_kill_app: %s', str(err))
+            # Let the app crash after providing a proper stack trace
+            raise err
+        raise urwid.ExitMainLoop()
+
+    def _set_status(self, msg: str) -> None:
+        """
+        Sets the message as the status.
+
+        :param msg:
+            The message to be displayed in the status bar.
+        """
+        self.window.footer.set_text(msg)
+
+    def _get_formatted_address(self) -> str:
+        """
+        Returns a formatted version of the server's address.
+
+        :return: formatted address
+        """
+        if isinstance(self.address, tuple):
+            host, port = self.address
+            addr = f'{host}:{port}'
+        else:
+            addr = f'{self.address}'
+        return addr
+
+    async def connect_server(self) -> None:
+        """
+        Initiates a connection to the server at address `self.address`
+        and in case of a failure, sets the status to the respective error.
+        """
+        try:
+            await self.connect(self.address)
+            addr = self._get_formatted_address()
+            self._set_status(f'Connected to {addr}')
+        except ConnectError as err:
+            logging.info('connect_server: ConnectError %s', str(err))
+            self._set_status(f'[ConnectError: {err.error_message}]')
+
+    def run(self, debug: bool = False) -> None:
+        """
+        Starts the long running co-routines and the urwid event loop.
+
+        :param debug:
+            Enables/Disables asyncio event loop debugging
+        """
+        self.aloop = asyncio.get_event_loop()
+        self.aloop.set_debug(debug)
+
+        # Gracefully handle SIGTERM and SIGINT signals
+        cancel_signals = [signal.SIGTERM, signal.SIGINT]
+        for sig in cancel_signals:
+            self.aloop.add_signal_handler(sig, self.kill_app)
+
+        event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
+        main_loop = urwid.MainLoop(urwid.AttrMap(self.window, 'background'),
+                                   unhandled_input=self.unhandled_input,
+                                   handle_mouse=True,
+                                   event_loop=event_loop)
+
+        create_task(self.wait_for_events(), self.aloop)
+        create_task(self.connect_server(), self.aloop)
+        try:
+            main_loop.run()
+        except Exception as err:
+            logging.error('%s\n%s\n', str(err), pretty_traceback())
+            raise err
+
+
+class StatusBar(urwid.Text):
+    """
+    A simple statusbar modelled using the Text widget. The status can be
+    set using the set_text function. All text set is aligned to right.
+    """
+    def __init__(self, text: str = ''):
+        super().__init__(text, align='right')
+
+
+class Editor(urwid_readline.ReadlineEdit):
+    """
+    A simple editor modelled using the urwid_readline.ReadlineEdit widget.
+    Mimcs GNU readline shortcuts and provides history support.
+
+    The readline shortcuts can be found below:
+    https://github.com/rr-/urwid_readline#features
+
+    Along with the readline features, this editor also has support for
+    history. Pressing the 'up' arrow key with empty message box, lists the
+    previous message inplace.
+
+    Currently there is no support to save the history to a file. The history of
+    previous commands is lost on exit.
+    """
+    def __init__(self, master: App) -> None:
+        """
+        Initializes the editor widget
+
+        :param master: Reference to the TUI object.
+        """
+        super().__init__(caption='> ', multiline=True)
+        self.master = master
+        self.history: List[str] = []
+        self.last_index: int = -1
+        self.show_history: bool = False
+
+    def keypress(self, size: Tuple[int, int], key: str) -> Optional[str]:
+        """
+        Handles the keypress on this widget.
+
+        :param size:
+            The current size of the widget.
+        :param key:
+            The key to be handled.
+
+        :return: Unhandled key if any.
+        """
+        # TODO: Add some logic for down key and clean up logic if possible.
+        # Returning None means the key has been handled by this widget
+        # which otherwise is propogated to the parent widget to be
+        # handled
+        msg = self.get_edit_text()
+        if key == 'up' and not msg:
+            # Show the history when 'up arrow' is pressed with no input text.
+            # NOTE: The show_history logic is necessary because in 'multiline'
+            # mode (which we use) 'up arrow' is used to move between lines.
+            self.show_history = True
+            last_msg = self.history[self.last_index] if self.history else ''
+            self.set_edit_text(last_msg)
+            self.edit_pos = len(last_msg)
+            self.last_index += 1
+        elif key == 'up' and self.show_history:
+            if self.last_index < len(self.history):
+                self.set_edit_text(self.history[self.last_index])
+                self.edit_pos = len(self.history[self.last_index])
+                self.last_index += 1
+        elif key == 'meta enter':
+            # When using multiline, enter inserts a new line into the editor
+            # send the input to the server on alt + enter
+            self.master.cb_send_to_server(msg)
+            self.history.insert(0, msg)
+            self.set_edit_text('')
+            self.last_index = 0
+            self.show_history = False
+        else:
+            self.show_history = False
+            self.last_index = 0
+            return cast(Optional[str], super().keypress(size, key))
+        return None
+
+
+class EditorWidget(urwid.Filler):
+    """
+    The Editor is a flow widget and has to wrapped inside a box widget.
+    This class wraps the Editor inside filler widget.
+    """
+    def __init__(self, master: App) -> None:
+        super().__init__(Editor(master), valign='top')
+
+
+class HistoryBox(urwid.ListBox):
+    """
+    This widget is modelled using the ListBox widget, contains the list of
+    all messages both QMP messages and log messsages to be shown in the TUI.
+
+    The messages are urwid.Text widgets. On every append of a message, the
+    focus is shifted to the last appended message.
+    """
+    def __init__(self, master: App) -> None:
+        """
+        Initializes the historybox widget
+
+        :param master: Reference to the TUI object.
+        """
+        self.master = master
+        self.history = urwid.SimpleFocusListWalker([])
+        super().__init__(self.history)
+
+    def add_to_history(self, history: str) -> None:
+        """
+        Appends a message to the list and set the focus to the last appended
+        message.
+
+        :param history:
+            The history item(message/event) to be appended to the list.
+        """
+        self.history.append(urwid.Text(history))
+        if self.history:
+            self.history.set_focus(len(self.history) - 1)
+
+
+class HistoryWindow(urwid.Frame):
+    """
+    This window composes the HistoryBox and EditorWidget in a horizontal split.
+    By default the first focus is given to the history box.
+    """
+    def __init__(self, master: App) -> None:
+        """
+        Initializes this widget and its child widgets.
+
+        :param master: Reference to the TUI object.
+        """
+        self.master = master
+        self.editor_widget = EditorWidget(master)
+        self.editor = urwid.LineBox(self.editor_widget)
+        self.history = HistoryBox(master)
+        self.body = urwid.Pile([('weight', 80, self.history),
+                                ('weight', 20, self.editor)])
+        super().__init__(self.body)
+        urwid.connect_signal(self.master, UPDATE_MSG, self.cb_add_to_history)
+
+    def cb_add_to_history(self, msg: str, level: Optional[str] = None) -> None:
+        """
+        Appends a message to the history box
+
+        :param msg:
+            The message to be appended to the history box.
+        """
+        if level:
+            msg = f'[{level}]: {msg}'
+        self.history.add_to_history(msg)
+
+
+class Window(urwid.Frame):
+    """
+    This window is the top most widget of the TUI and will contain other
+    windows. Each window is responsible for displaying a specific
+    functionality.
+    For eg: The history window is responsible for showing the history of
+    messages and the editor.
+    """
+    def __init__(self, master: App) -> None:
+        """
+        Initializes this widget and its child windows.
+
+        :param master: Reference to the TUI object.
+        """
+        self.master = master
+        footer = StatusBar()
+        body = HistoryWindow(master)
+        super().__init__(body, footer=footer)
+
+
+class TUILogHandler(Handler):
+    """
+    This handler routes all the log messages to the TUI screen.
+    It is installed to the root logger to so that the log message from all
+    libraries begin used is routed to the screen.
+    """
+    def __init__(self, tui: App) -> None:
+        """
+        Initializes the handler class.
+
+        :param tui:
+            Reference to the TUI object.
+        """
+        super().__init__()
+        self.tui = tui
+
+    def emit(self, record: LogRecord) -> None:
+        """
+        Emits a record to the TUI screen.
+
+        Appends the log message to the TUI screen
+        """
+        level = record.levelname
+        msg = record.getMessage()
+        self.tui.add_to_history(msg, level)
+
+
+def main() -> None:
+    """
+    Driver of the whole script, parses arguments, initialize the TUI and
+    the logger.
+    """
+    parser = argparse.ArgumentParser(description='AQMP TUI')
+    parser.add_argument('qmp_server', help='Address of the QMP server. '
+                        'Format <UNIX socket path | TCP addr:port>')
+    parser.add_argument('--log-file', help='The Log file name')
+    parser.add_argument('--log-level', default='WARNING',
+                        help='Log level <CRITICAL|ERROR|WARNING|INFO|DEBUG|>')
+    parser.add_argument('--asyncio-debug', action='store_true',
+                        help='Enable debug mode for asyncio loop. '
+                        'Generates lot of output, makes TUI unusable when '
+                        'logs are logged in the TUI. '
+                        'Use only when logging to a file.')
+    args = parser.parse_args()
+
+    try:
+        address = QEMUMonitorProtocol.parse_address(args.qmp_server)
+    except QMPBadPortError as err:
+        parser.error(str(err))
+
+    app = App(address)
+
+    root_logger = logging.getLogger()
+    root_logger.setLevel(logging.getLevelName(args.log_level))
+
+    if args.log_file:
+        root_logger.addHandler(logging.FileHandler(args.log_file))
+    else:
+        root_logger.addHandler(TUILogHandler(app))
+
+    app.run(args.asyncio_debug)
+
+
+if __name__ == '__main__':
+    main()
diff --git a/python/setup.cfg b/python/setup.cfg
index a0ed3279d8..1ff2b907a2 100644
--- a/python/setup.cfg
+++ b/python/setup.cfg
@@ -81,8 +81,19 @@ namespace_packages = True
 # fusepy has no type stubs:
 allow_subclassing_any = True
 
+[mypy-qemu.aqmp.aqmp_tui]
+# urwid and urwid_readline have no type stubs:
+allow_subclassing_any = True
+
+# The following missing import directives are because these libraries do not
+# provide type stubs. Allow them on an as-needed basis for mypy.
 [mypy-fuse]
-# fusepy has no type stubs:
+ignore_missing_imports = True
+
+[mypy-urwid]
+ignore_missing_imports = True
+
+[mypy-urwid_readline]
 ignore_missing_imports = True
 
 [pylint.messages control]
@@ -97,7 +108,7 @@ ignore_missing_imports = True
 # --disable=W".
 disable=too-many-function-args,  # mypy handles this with less false positives.
         no-member,  # mypy also handles this better.
-        missing-docstring, # FIXME
+        # missing-docstring, # FIXME
         fixme, # FIXME
 
 [pylint.basic]
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v4 4/7] python: Add entry point for aqmp-tui
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
                   ` (2 preceding siblings ...)
  2021-08-19 17:38 ` [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 5/7] python: add optional pygments dependency G S Niteesh Babu
                   ` (3 subsequent siblings)
  7 siblings, 0 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Add an entry point for aqmp-tui. This will allow it to be run from
the command line using "aqmp-tui localhost:1234"
More options available in the TUI can be found using "aqmp-tui -h"

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/setup.cfg | 1 +
 1 file changed, 1 insertion(+)

diff --git a/python/setup.cfg b/python/setup.cfg
index 1ff2b907a2..64ed0be0a7 100644
--- a/python/setup.cfg
+++ b/python/setup.cfg
@@ -66,6 +66,7 @@ console_scripts =
     qom-fuse = qemu.qmp.qom_fuse:QOMFuse.entry_point [fuse]
     qemu-ga-client = qemu.qmp.qemu_ga_client:main
     qmp-shell = qemu.qmp.qmp_shell:main
+    aqmp-tui = qemu.aqmp.aqmp_tui:main [tui]
 
 [flake8]
 extend-ignore = E722  # Prefer pylint's bare-except checks to flake8's
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v4 5/7] python: add optional pygments dependency
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
                   ` (3 preceding siblings ...)
  2021-08-19 17:38 ` [PATCH v4 4/7] python: Add entry point for aqmp-tui G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 6/7] python/aqmp-tui: Add syntax highlighting G S Niteesh Babu
                   ` (2 subsequent siblings)
  7 siblings, 0 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Added pygments as optional dependency for AQMP TUI.
This is required for the upcoming syntax highlighting feature
in AQMP TUI.
The dependency has also been added in the devel optional group.

Added mypy 'ignore_missing_imports' for pygments since it does
not have any type stubs.

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/Pipfile.lock | 8 ++++++++
 python/setup.cfg    | 5 +++++
 2 files changed, 13 insertions(+)

diff --git a/python/Pipfile.lock b/python/Pipfile.lock
index da7a4ee164..d2a7dbd88b 100644
--- a/python/Pipfile.lock
+++ b/python/Pipfile.lock
@@ -200,6 +200,14 @@
             ],
             "version": "==2.0.0"
         },
+        "pygments": {
+            "hashes": [
+                "sha256:a18f47b506a429f6f4b9df81bb02beab9ca21d0a5fee38ed15aef65f0545519f",
+                "sha256:d66e804411278594d764fc69ec36ec13d9ae9147193a1740cd34d272ca383b8e"
+            ],
+            "markers": "python_version >= '3.5'",
+            "version": "==2.9.0"
+        },
         "pylint": {
             "hashes": [
                 "sha256:082a6d461b54f90eea49ca90fff4ee8b6e45e8029e5dbd72f6107ef84f3779c0",
diff --git a/python/setup.cfg b/python/setup.cfg
index 64ed0be0a7..1c2e879a4c 100644
--- a/python/setup.cfg
+++ b/python/setup.cfg
@@ -46,6 +46,7 @@ devel =
     tox >= 3.18.0
     urwid >= 2.1.2
     urwid-readline >= 0.13
+    Pygments >= 2.9.0
 
 # Provides qom-fuse functionality
 fuse =
@@ -55,6 +56,7 @@ fuse =
 tui =
     urwid >= 2.1.2
     urwid-readline >= 0.13
+    Pygments >= 2.9.0
 
 [options.entry_points]
 console_scripts =
@@ -97,6 +99,9 @@ ignore_missing_imports = True
 [mypy-urwid_readline]
 ignore_missing_imports = True
 
+[mypy-pygments]
+ignore_missing_imports = True
+
 [pylint.messages control]
 # Disable the message, report, category or checker with the given id(s). You
 # can either give multiple identifiers separated by comma (,) or put this
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v4 6/7] python/aqmp-tui: Add syntax highlighting
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
                   ` (4 preceding siblings ...)
  2021-08-19 17:38 ` [PATCH v4 5/7] python: add optional pygments dependency G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-19 17:38 ` [PATCH v4 7/7] python/aqmp-tui: Add QMP connection manager G S Niteesh Babu
  2021-08-21  4:09 ` [PATCH v4 0/7] AQMP TUI Draft John Snow
  7 siblings, 0 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

Add syntax highlighting for the incoming and outgoing QMP messages.
This is achieved using the pygments module which was added in a
previous commit.

The current implementation is a really simple one which doesn't
allow for any configuration. In future this has to be improved
to allow for easier theme config using an external config of
some sort.

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/qemu/aqmp/aqmp_tui.py | 36 ++++++++++++++++++++++++++++++++++--
 1 file changed, 34 insertions(+), 2 deletions(-)

diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
index 12c9c4162a..03d4808acd 100644
--- a/python/qemu/aqmp/aqmp_tui.py
+++ b/python/qemu/aqmp/aqmp_tui.py
@@ -29,6 +29,8 @@
     cast,
 )
 
+from pygments import lexers
+from pygments import token as Token
 import urwid
 import urwid_readline
 
@@ -43,6 +45,22 @@
 UPDATE_MSG: str = 'UPDATE_MSG'
 
 
+palette = [
+    (Token.Punctuation, '', '', '', 'h15,bold', 'g7'),
+    (Token.Text, '', '', '', '', 'g7'),
+    (Token.Name.Tag, '', '', '', 'bold,#f88', 'g7'),
+    (Token.Literal.Number.Integer, '', '', '', '#fa0', 'g7'),
+    (Token.Literal.String.Double, '', '', '', '#6f6', 'g7'),
+    (Token.Keyword.Constant, '', '', '', '#6af', 'g7'),
+    ('DEBUG', '', '', '', '#ddf', 'g7'),
+    ('INFO', '', '', '', 'g100', 'g7'),
+    ('WARNING', '', '', '', '#ff6', 'g7'),
+    ('ERROR', '', '', '', '#a00', 'g7'),
+    ('CRITICAL', '', '', '', '#a00', 'g7'),
+    ('background', '', 'black', '', '', 'g7'),
+]
+
+
 def format_json(msg: str) -> str:
     """
     Formats given multi-line JSON message into a single-line message.
@@ -303,6 +321,9 @@ def run(self, debug: bool = False) -> None:
         :param debug:
             Enables/Disables asyncio event loop debugging
         """
+        screen = urwid.raw_display.Screen()
+        screen.set_terminal_properties(256)
+
         self.aloop = asyncio.get_event_loop()
         self.aloop.set_debug(debug)
 
@@ -314,6 +335,8 @@ def run(self, debug: bool = False) -> None:
         event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
         main_loop = urwid.MainLoop(urwid.AttrMap(self.window, 'background'),
                                    unhandled_input=self.unhandled_input,
+                                   screen=screen,
+                                   palette=palette,
                                    handle_mouse=True,
                                    event_loop=event_loop)
 
@@ -434,7 +457,8 @@ def __init__(self, master: App) -> None:
         self.history = urwid.SimpleFocusListWalker([])
         super().__init__(self.history)
 
-    def add_to_history(self, history: str) -> None:
+    def add_to_history(self,
+                       history: Union[str, List[Tuple[str, str]]]) -> None:
         """
         Appends a message to the list and set the focus to the last appended
         message.
@@ -473,10 +497,18 @@ def cb_add_to_history(self, msg: str, level: Optional[str] = None) -> None:
 
         :param msg:
             The message to be appended to the history box.
+        :param level:
+            The log level of the message, if it is a log message.
         """
+        formatted = []
         if level:
             msg = f'[{level}]: {msg}'
-        self.history.add_to_history(msg)
+            formatted.append((level, msg))
+        else:
+            lexer = lexers.JsonLexer()  # pylint: disable=no-member
+            for token in lexer.get_tokens(msg):
+                formatted.append(token)
+        self.history.add_to_history(formatted)
 
 
 class Window(urwid.Frame):
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* [PATCH v4 7/7] python/aqmp-tui: Add QMP connection manager
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
                   ` (5 preceding siblings ...)
  2021-08-19 17:38 ` [PATCH v4 6/7] python/aqmp-tui: Add syntax highlighting G S Niteesh Babu
@ 2021-08-19 17:38 ` G S Niteesh Babu
  2021-08-21  4:09 ` [PATCH v4 0/7] AQMP TUI Draft John Snow
  7 siblings, 0 replies; 15+ messages in thread
From: G S Niteesh Babu @ 2021-08-19 17:38 UTC (permalink / raw)
  To: qemu-devel
  Cc: ehabkost, kchamart, jsnow, armbru, wainersm, G S Niteesh Babu,
	stefanha, crosa, eblake

The connection manager will take care of connecting/disconnecting
to the server. This will also try to reconnect to the server in
certain situations where the client has been disconnected due to
some error condition.

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
 python/qemu/aqmp/aqmp_tui.py | 127 +++++++++++++++++++++++++++++------
 1 file changed, 105 insertions(+), 22 deletions(-)

diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
index 03d4808acd..c47abe0a25 100644
--- a/python/qemu/aqmp/aqmp_tui.py
+++ b/python/qemu/aqmp/aqmp_tui.py
@@ -35,8 +35,9 @@
 import urwid_readline
 
 from ..qmp import QEMUMonitorProtocol, QMPBadPortError
+from .error import ProtocolError
 from .message import DeserializationError, Message, UnexpectedTypeError
-from .protocol import ConnectError
+from .protocol import ConnectError, Runstate
 from .qmp_client import ExecInterruptedError, QMPClient
 from .util import create_task, pretty_traceback
 
@@ -128,17 +129,26 @@ class App(QMPClient):
 
     Initializes the widgets and starts the urwid event loop.
     """
-    def __init__(self, address: Union[str, Tuple[str, int]]) -> None:
+    def __init__(self, address: Union[str, Tuple[str, int]], num_retries: int,
+                 retry_delay: Optional[int]) -> None:
         """
         Initializes the TUI.
 
         :param address:
             Address of the server to connect to.
+        :param num_retries:
+            The number of times to retry before stopping to reconnect.
+        :param retry_delay:
+            The delay(sec) before each retry
         """
         urwid.register_signal(type(self), UPDATE_MSG)
         self.window = Window(self)
         self.address = address
         self.aloop: Optional[asyncio.AbstractEventLoop] = None
+        self.num_retries = num_retries
+        self.retry_delay = retry_delay if retry_delay else 2
+        self.retry: bool = False
+        self.disconnecting: bool = False
         super().__init__()
 
     def add_to_history(self, msg: str, level: Optional[str] = None) -> None:
@@ -212,10 +222,10 @@ def handle_event(self, event: Message) -> None:
         """
         try:
             await self._raw(msg, assign_id='id' not in msg)
-        except ExecInterruptedError:
-            logging.info('Error server disconnected before reply')
+        except ExecInterruptedError as err:
+            logging.info('Error server disconnected before reply %s', str(err))
             self.add_to_history('Server disconnected before reply', 'ERROR')
-            self._set_status("[Server Disconnected]")
+            await self.disconnect()
         except Exception as err:
             logging.error('Exception from _send_to_server: %s', str(err))
             raise err
@@ -237,10 +247,10 @@ def cb_send_to_server(self, raw_msg: str) -> None:
             create_task(self._send_to_server(msg))
         except (ValueError, TypeError) as err:
             logging.info('Invalid message: %s', str(err))
-            self.add_to_history(f'{raw_msg}: {err}')
+            self.add_to_history(f'{raw_msg}: {err}', 'ERROR')
         except (DeserializationError, UnexpectedTypeError) as err:
             logging.info('Invalid message: %s', err.error_message)
-            self.add_to_history(f'{raw_msg}: {err.error_message}')
+            self.add_to_history(f'{raw_msg}: {err.error_message}', 'ERROR')
 
     def unhandled_input(self, key: str) -> None:
         """
@@ -266,18 +276,32 @@ def kill_app(self) -> None:
 
         :raise Exception: When an unhandled exception is caught.
         """
-        # It is ok to call disconnect even in disconnect state
+        await self.disconnect()
+        logging.debug('Disconnect finished. Exiting app')
+        raise urwid.ExitMainLoop()
+
+    async def disconnect(self) -> None:
+        """
+        Overrides the disconnect method to handle the errors locally.
+        """
+        if self.disconnecting:
+            return
         try:
-            await self.disconnect()
-            logging.debug('Disconnect finished. Exiting app')
-        except EOFError:
-            # We receive an EOF during disconnect, ignore that
-            pass
+            self.disconnecting = True
+            await super().disconnect()
+            self.retry = False
+        except EOFError as err:
+            logging.info('disconnect: %s', str(err))
+            self.retry = True
+        except ProtocolError as err:
+            logging.info('disconnect: %s', str(err))
+            self.retry = False
         except Exception as err:
-            logging.info('_kill_app: %s', str(err))
-            # Let the app crash after providing a proper stack trace
+            logging.error('disconnect: Unhandled exception %s', str(err))
+            self.retry = False
             raise err
-        raise urwid.ExitMainLoop()
+        finally:
+            self.disconnecting = False
 
     def _set_status(self, msg: str) -> None:
         """
@@ -301,18 +325,72 @@ def _get_formatted_address(self) -> str:
             addr = f'{self.address}'
         return addr
 
-    async def connect_server(self) -> None:
+    async def _initiate_connection(self) -> Optional[ConnectError]:
+        """
+        Tries connecting to a server a number of times with a delay between
+        each try. If all retries failed then return the error faced during
+        the last retry.
+
+        :return: Error faced during last retry.
+        """
+        current_retries = 0
+        err = None
+
+        # initial try
+        await self.connect_server()
+        while self.retry and current_retries < self.num_retries:
+            logging.info('Connection Failed, retrying in %d', self.retry_delay)
+            status = f'[Retry #{current_retries} ({self.retry_delay}s)]'
+            self._set_status(status)
+
+            await asyncio.sleep(self.retry_delay)
+
+            err = await self.connect_server()
+            current_retries += 1
+        # If all retries failed report the last error
+        if err:
+            logging.info('All retries failed: %s', err)
+            return err
+        return None
+
+    async def manage_connection(self) -> None:
+        """
+        Manage the connection based on the current run state.
+
+        A reconnect is issued when the current state is IDLE and the number
+        of retries is not exhausted.
+        A disconnect is issued when the current state is DISCONNECTING.
+        """
+        while True:
+            if self.runstate == Runstate.IDLE:
+                err = await self._initiate_connection()
+                # If retry is still true then, we have exhausted all our tries.
+                if err:
+                    self._set_status(f'[Error: {err.error_message}]')
+                else:
+                    addr = self._get_formatted_address()
+                    self._set_status(f'[Connected {addr}]')
+            elif self.runstate == Runstate.DISCONNECTING:
+                self._set_status('[Disconnected]')
+                await self.disconnect()
+                # check if a retry is needed
+                if self.runstate == Runstate.IDLE:
+                    continue
+            await self.runstate_changed()
+
+    async def connect_server(self) -> Optional[ConnectError]:
         """
         Initiates a connection to the server at address `self.address`
         and in case of a failure, sets the status to the respective error.
         """
         try:
             await self.connect(self.address)
-            addr = self._get_formatted_address()
-            self._set_status(f'Connected to {addr}')
+            self.retry = False
         except ConnectError as err:
             logging.info('connect_server: ConnectError %s', str(err))
-            self._set_status(f'[ConnectError: {err.error_message}]')
+            self.retry = True
+            return err
+        return None
 
     def run(self, debug: bool = False) -> None:
         """
@@ -341,7 +419,7 @@ def run(self, debug: bool = False) -> None:
                                    event_loop=event_loop)
 
         create_task(self.wait_for_events(), self.aloop)
-        create_task(self.connect_server(), self.aloop)
+        create_task(self.manage_connection(), self.aloop)
         try:
             main_loop.run()
         except Exception as err:
@@ -566,6 +644,11 @@ def main() -> None:
     parser = argparse.ArgumentParser(description='AQMP TUI')
     parser.add_argument('qmp_server', help='Address of the QMP server. '
                         'Format <UNIX socket path | TCP addr:port>')
+    parser.add_argument('--num-retries', type=int, default=10,
+                        help='Number of times to reconnect before giving up.')
+    parser.add_argument('--retry-delay', type=int,
+                        help='Time(s) to wait before next retry. '
+                        'Default action is to wait 2s between each retry.')
     parser.add_argument('--log-file', help='The Log file name')
     parser.add_argument('--log-level', default='WARNING',
                         help='Log level <CRITICAL|ERROR|WARNING|INFO|DEBUG|>')
@@ -581,7 +664,7 @@ def main() -> None:
     except QMPBadPortError as err:
         parser.error(str(err))
 
-    app = App(address)
+    app = App(address, args.num_retries, args.retry_delay)
 
     root_logger = logging.getLogger()
     root_logger.setLevel(logging.getLevelName(args.log_level))
-- 
2.17.1



^ permalink raw reply related	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 0/7] AQMP TUI Draft
  2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
                   ` (6 preceding siblings ...)
  2021-08-19 17:38 ` [PATCH v4 7/7] python/aqmp-tui: Add QMP connection manager G S Niteesh Babu
@ 2021-08-21  4:09 ` John Snow
  2021-08-21 21:20   ` Niteesh G. S.
  7 siblings, 1 reply; 15+ messages in thread
From: John Snow @ 2021-08-21  4:09 UTC (permalink / raw)
  To: G S Niteesh Babu
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 1839 bytes --]

On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
wrote:

> Hello all,
>
> Gitlab: https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v4
> CI: https://gitlab.com/niteesh.gs/qemu/-/pipelines/356024270
>
> Revision since v3:
> 1) Added docstrings
> 2) Minor changes in AQMP TUI Draft
> 3) Switched to constant retry delay in QMP connection manager and other
>    minor changes.
>
> G S Niteesh Babu (7):
>   python: disable pylint errors for aqmp-tui
>   python: Add dependencies for AQMP TUI
>   python/aqmp-tui: Add AQMP TUI draft
>   python: Add entry point for aqmp-tui
>   python: add optional pygments dependency
>   python/aqmp-tui: Add syntax highlighting
>   python/aqmp-tui: Add QMP connection manager
>
>  python/Pipfile.lock          |  20 +
>  python/qemu/aqmp/aqmp_tui.py | 681 +++++++++++++++++++++++++++++++++++
>  python/setup.cfg             |  29 +-
>  3 files changed, 729 insertions(+), 1 deletion(-)
>  create mode 100644 python/qemu/aqmp/aqmp_tui.py
>
> --
> 2.17.1
>
>
Hiya, please specify what your branch is based on when you submit your
patchsets using the Based-On tag.

- It's time to drop patch #1 entirely.
- We can drop the word 'draft' from the commit messages now, let's try to
make this solid.
- If you want to keep the TODO comments in the code, add a pylint
configuration item that allows "todo" but disallows "fixme" and "xxx"
comments.

Detailed review to follow tomorrow, but you can start working on these
items right away. I might also squash patch #7 directly into patch #3, but
haven't looked too closely yet.

(Note that due to an update to pylint that happened just today, check-tox
is going to fail now -- that's fine, it's not your fault. As long as
check-pipenv works, you're in good shape. I'll have a fix in my python
branch tomorrow for these problems.)

[-- Attachment #2: Type: text/html, Size: 2663 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 2/7] python: Add dependencies for AQMP TUI
  2021-08-19 17:38 ` [PATCH v4 2/7] python: Add dependencies for AQMP TUI G S Niteesh Babu
@ 2021-08-21 19:54   ` John Snow
  0 siblings, 0 replies; 15+ messages in thread
From: John Snow @ 2021-08-21 19:54 UTC (permalink / raw)
  To: G S Niteesh Babu
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 426 bytes --]

On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
wrote:

> Added dependencies for the upcoming AQMP TUI under the optional
> 'tui' group.
>
> The same dependencies have also been added under the devel group
> since no work around has been found for optional groups to imply
> other optional groups.
>
> Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
>

Reviewed-by: John Snow <jsnow@redhat.com>

[-- Attachment #2: Type: text/html, Size: 912 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft
  2021-08-19 17:38 ` [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft G S Niteesh Babu
@ 2021-08-21 20:05   ` John Snow
  2021-08-21 22:21     ` Niteesh G. S.
  2021-08-22  7:33   ` John Snow
  1 sibling, 1 reply; 15+ messages in thread
From: John Snow @ 2021-08-21 20:05 UTC (permalink / raw)
  To: G S Niteesh Babu
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 22831 bytes --]

On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
wrote:

> Added a draft of AQMP TUI.
>
> Implements the follwing basic features:
> 1) Command transmission/reception.
> 2) Shows events asynchronously.
> 3) Shows server status in the bottom status bar.
>
> Also added type annotations and necessary pylint,
> mypy configurations
>
> Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
> ---
>  python/qemu/aqmp/aqmp_tui.py | 566 +++++++++++++++++++++++++++++++++++
>  python/setup.cfg             |  15 +-
>  2 files changed, 579 insertions(+), 2 deletions(-)
>  create mode 100644 python/qemu/aqmp/aqmp_tui.py
>
> diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
> new file mode 100644
> index 0000000000..12c9c4162a
> --- /dev/null
> +++ b/python/qemu/aqmp/aqmp_tui.py
> @@ -0,0 +1,566 @@
> +# Copyright (c) 2021
> +#
> +# Authors:
> +#  Niteesh Babu G S <niteesh.gs@gmail.com>
> +#
> +# This work is licensed under the terms of the GNU GPL, version 2 or
> +# later.  See the COPYING file in the top-level directory.
> +"""
> +AQMP TUI
> +
> +AQMP TUI is an asynchronous interface built on top the of the AQMP
> library.
> +It is the successor of QMP-shell and is bought-in as a replacement for it.
> +
> +Example Usage: aqmp-tui <SOCKET | TCP IP:PORT>
> +Full Usage: aqmp-tui --help
> +"""
> +
> +import argparse
> +import asyncio
> +import logging
> +from logging import Handler, LogRecord
> +import signal
> +from typing import (
> +    List,
> +    Optional,
> +    Tuple,
> +    Type,
> +    Union,
> +    cast,
> +)
> +
> +import urwid
> +import urwid_readline
> +
> +from ..qmp import QEMUMonitorProtocol, QMPBadPortError
> +from .message import DeserializationError, Message, UnexpectedTypeError
> +from .protocol import ConnectError
> +from .qmp_client import ExecInterruptedError, QMPClient
> +from .util import create_task, pretty_traceback
> +
> +
> +# The name of the signal that is used to update the history list
> +UPDATE_MSG: str = 'UPDATE_MSG'
> +
> +
> +def format_json(msg: str) -> str:
> +    """
> +    Formats given multi-line JSON message into a single-line message.
> +    Converting into single line is more asthetically pleasing when looking
> +    along with error messages.
> +
> +    Eg:
> +    Input:
> +          [ 1,
> +            true,
> +            3 ]
> +    The above input is not a valid QMP message and produces the following
> error
> +    "QMP message is not a JSON object."
> +    When displaying this in TUI in multiline mode we get
> +
> +        [ 1,
> +          true,
> +          3 ]: QMP message is not a JSON object.
> +
> +    whereas in singleline mode we get the following
> +
> +        [1, true, 3]: QMP message is not a JSON object.
> +
> +    The single line mode is more asthetically pleasing.
> +
> +    :param msg:
> +        The message to formatted into single line.
> +
> +    :return: Formatted singleline message.
> +
> +    NOTE: We cannot use the JSON module here because it is only capable of
> +    format valid JSON messages. But here the goal is to also format
> invalid
> +    JSON messages.
> +    """
> +    msg = msg.replace('\n', '')
> +    words = msg.split(' ')
> +    words = [word for word in words if word != '']
> +    return ' '.join(words)
> +
> +
> +def has_tui_handler(logger: logging.Logger,
> +                    handler_type: Type[Handler]) -> bool:
> +    """
> +    The Logger class has no interface to check if a certain type of
> handler is
> +    installed or not. So we provide an interface to do so.
> +
> +    :param logger:
> +        Logger object
> +    :param handler_type:
> +        The type of the handler to be checked.
> +
> +    :return: returns True if handler of type `handler_type` is installed
> else
> +             False.
> +    """
> +    handlers = logger.handlers
> +    for handler in handlers:
> +        if isinstance(handler, handler_type):
> +            return True
> +    return False
> +
> +
> +class App(QMPClient):
> +    """
> +    Implements the AQMP TUI.
> +
> +    Initializes the widgets and starts the urwid event loop.
> +    """
> +    def __init__(self, address: Union[str, Tuple[str, int]]) -> None:
> +        """
> +        Initializes the TUI.
> +
> +        :param address:
> +            Address of the server to connect to.
> +        """
> +        urwid.register_signal(type(self), UPDATE_MSG)
> +        self.window = Window(self)
> +        self.address = address
> +        self.aloop: Optional[asyncio.AbstractEventLoop] = None
> +        super().__init__()
> +
> +    def add_to_history(self, msg: str, level: Optional[str] = None) ->
> None:
> +        """
> +        Appends the msg to the history list.
> +
> +        :param msg:
> +            The raw message to be appended in string type.
> +        """
> +        urwid.emit_signal(self, UPDATE_MSG, msg, level)
> +
> +    def _cb_outbound(self, msg: Message) -> Message:
> +        """
> +        Callback: outbound message hook.
> +
> +        Appends the outgoing messages to the history box.
> +
> +        :param msg: raw outbound message.
> +        :return: final outbound message.
> +        """
> +        str_msg = str(msg)
> +
> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
> +            logging.debug('Request: %s', str_msg)
> +        self.add_to_history('<-- ' + str_msg)
> +        return msg
> +
> +    def _cb_inbound(self, msg: Message) -> Message:
> +        """
> +        Callback: outbound message hook.
> +
> +        Appends the incoming messages to the history box.
> +
> +        :param msg: raw inbound message.
> +        :return: final inbound message.
> +        """
> +        str_msg = str(msg)
> +
> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
> +            logging.debug('Request: %s', str_msg)
> +        self.add_to_history('--> ' + str_msg)
> +        return msg
> +
>

Starting here: ...


> +    def handle_event(self, event: Message) -> None:
> +        """
> +        Handles the event.
> +
> +        :param event:
> +            The event to be handled.
> +        """
> +        # TODO: Consider all states present in qapi/run-state.json
> +        if event['event'] == 'SHUTDOWN':
> +            self._set_status('[Server Shutdown]')
> +
> +    async def wait_for_events(self) -> None:
> +        """
> +        This coroutine continously waits for events and dispatches them.
> +        """
> +        async for event in self.events:
> +            self.handle_event(event)
> +
>

... until here, we can remove these from this series, because we don't use
them for anything by the end of this series. We can re-add them once that
"TODO" is done.


> +    async def _send_to_server(self, msg: Message) -> None:
> +        """
> +        This coroutine sends the message to the server.
> +        The message has to be pre-validated.
> +
> +        :param msg:
> +            Pre-validated message to be to sent to the server.
> +
> +        :raise Exception: When an unhandled exception is caught.
> +        """
> +        try:
> +            await self._raw(msg, assign_id='id' not in msg)
> +        except ExecInterruptedError:
> +            logging.info('Error server disconnected before reply')
> +            self.add_to_history('Server disconnected before reply',
> 'ERROR')
> +            self._set_status("[Server Disconnected]")
> +        except Exception as err:
> +            logging.error('Exception from _send_to_server: %s', str(err))
> +            raise err
> +
> +    def cb_send_to_server(self, raw_msg: str) -> None:
> +        """
> +        Validates and sends the message to the server.
> +        The raw string message is first converted into a Message object
> +        and is then sent to the server.
> +
> +        :param raw_msg:
> +            The raw string message to be sent to the server.
> +
> +        :raise Exception: When an unhandled exception is caught.
> +        """
> +        try:
> +            raw_msg = format_json(raw_msg)
> +            msg = Message(bytes(raw_msg, encoding='utf-8'))
> +            create_task(self._send_to_server(msg))
> +        except (ValueError, TypeError) as err:
> +            logging.info('Invalid message: %s', str(err))
> +            self.add_to_history(f'{raw_msg}: {err}')
> +        except (DeserializationError, UnexpectedTypeError) as err:
> +            logging.info('Invalid message: %s', err.error_message)
> +            self.add_to_history(f'{raw_msg}: {err.error_message}')
> +
> +    def unhandled_input(self, key: str) -> None:
> +        """
> +        Handle's keys which haven't been handled by the child widgets.
> +
> +        :param key:
> +            Unhandled key
> +        """
> +        if key == 'esc':
> +            self.kill_app()
> +
> +    def kill_app(self) -> None:
> +        """
> +        Initiates killing of app. A bridge between asynchronous and
> synchronous
> +        code.
> +        """
> +        create_task(self._kill_app())
> +
> +    async def _kill_app(self) -> None:
> +        """
> +        This coroutine initiates the actual disconnect process and calls
> +        urwid.ExitMainLoop() to kill the TUI.
> +
> +        :raise Exception: When an unhandled exception is caught.
> +        """
> +        # It is ok to call disconnect even in disconnect state
> +        try:
> +            await self.disconnect()
> +            logging.debug('Disconnect finished. Exiting app')
> +        except EOFError:
> +            # We receive an EOF during disconnect, ignore that
> +            pass
> +        except Exception as err:
> +            logging.info('_kill_app: %s', str(err))
> +            # Let the app crash after providing a proper stack trace
> +            raise err
> +        raise urwid.ExitMainLoop()
> +
> +    def _set_status(self, msg: str) -> None:
> +        """
> +        Sets the message as the status.
> +
> +        :param msg:
> +            The message to be displayed in the status bar.
> +        """
> +        self.window.footer.set_text(msg)
> +
> +    def _get_formatted_address(self) -> str:
> +        """
> +        Returns a formatted version of the server's address.
> +
> +        :return: formatted address
> +        """
> +        if isinstance(self.address, tuple):
> +            host, port = self.address
> +            addr = f'{host}:{port}'
> +        else:
> +            addr = f'{self.address}'
> +        return addr
> +
> +    async def connect_server(self) -> None:
> +        """
> +        Initiates a connection to the server at address `self.address`
> +        and in case of a failure, sets the status to the respective error.
> +        """
> +        try:
> +            await self.connect(self.address)
> +            addr = self._get_formatted_address()
> +            self._set_status(f'Connected to {addr}')
> +        except ConnectError as err:
> +            logging.info('connect_server: ConnectError %s', str(err))
> +            self._set_status(f'[ConnectError: {err.error_message}]')
> +
> +    def run(self, debug: bool = False) -> None:
> +        """
> +        Starts the long running co-routines and the urwid event loop.
> +
> +        :param debug:
> +            Enables/Disables asyncio event loop debugging
> +        """
> +        self.aloop = asyncio.get_event_loop()
> +        self.aloop.set_debug(debug)
> +
> +        # Gracefully handle SIGTERM and SIGINT signals
> +        cancel_signals = [signal.SIGTERM, signal.SIGINT]
> +        for sig in cancel_signals:
> +            self.aloop.add_signal_handler(sig, self.kill_app)
> +
> +        event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
> +        main_loop = urwid.MainLoop(urwid.AttrMap(self.window,
> 'background'),
> +                                   unhandled_input=self.unhandled_input,
> +                                   handle_mouse=True,
> +                                   event_loop=event_loop)
> +
> +        create_task(self.wait_for_events(), self.aloop)
>

This can be removed since it isn't used for anything by the end of this
series. We can re-add the event watcher when the status updater is actually
completed.


> +        create_task(self.connect_server(), self.aloop)
> +        try:
> +            main_loop.run()
> +        except Exception as err:
> +            logging.error('%s\n%s\n', str(err), pretty_traceback())
> +            raise err
> +
> +
> +class StatusBar(urwid.Text):
> +    """
> +    A simple statusbar modelled using the Text widget. The status can be
> +    set using the set_text function. All text set is aligned to right.
> +    """
> +    def __init__(self, text: str = ''):
> +        super().__init__(text, align='right')
> +
> +
> +class Editor(urwid_readline.ReadlineEdit):
> +    """
> +    A simple editor modelled using the urwid_readline.ReadlineEdit widget.
> +    Mimcs GNU readline shortcuts and provides history support.
> +
> +    The readline shortcuts can be found below:
> +    https://github.com/rr-/urwid_readline#features
> +
> +    Along with the readline features, this editor also has support for
> +    history. Pressing the 'up' arrow key with empty message box, lists the
> +    previous message inplace.
> +
> +    Currently there is no support to save the history to a file. The
> history of
> +    previous commands is lost on exit.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes the editor widget
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        super().__init__(caption='> ', multiline=True)
> +        self.master = master
> +        self.history: List[str] = []
> +        self.last_index: int = -1
> +        self.show_history: bool = False
> +
> +    def keypress(self, size: Tuple[int, int], key: str) -> Optional[str]:
> +        """
> +        Handles the keypress on this widget.
> +
> +        :param size:
> +            The current size of the widget.
> +        :param key:
> +            The key to be handled.
> +
> +        :return: Unhandled key if any.
> +        """
> +        # TODO: Add some logic for down key and clean up logic if
> possible.
>

What logic needs to be added here? Can this comment be made more explicit?
What kind of cleanup do we need to do here, still?
(Is now the right time to do that cleanup, or not?)

If you want to leave the TODO in, then edit setup.cfg and add the exemption
for it.


> +        # Returning None means the key has been handled by this widget
> +        # which otherwise is propogated to the parent widget to be
> +        # handled
> +        msg = self.get_edit_text()
> +        if key == 'up' and not msg:
> +            # Show the history when 'up arrow' is pressed with no input
> text.
> +            # NOTE: The show_history logic is necessary because in
> 'multiline'
> +            # mode (which we use) 'up arrow' is used to move between
> lines.
> +            self.show_history = True
> +            last_msg = self.history[self.last_index] if self.history else
> ''
> +            self.set_edit_text(last_msg)
> +            self.edit_pos = len(last_msg)
> +            self.last_index += 1
> +        elif key == 'up' and self.show_history:
> +            if self.last_index < len(self.history):
> +                self.set_edit_text(self.history[self.last_index])
> +                self.edit_pos = len(self.history[self.last_index])
> +                self.last_index += 1
> +        elif key == 'meta enter':
> +            # When using multiline, enter inserts a new line into the
> editor
> +            # send the input to the server on alt + enter
> +            self.master.cb_send_to_server(msg)
> +            self.history.insert(0, msg)
> +            self.set_edit_text('')
> +            self.last_index = 0
> +            self.show_history = False
> +        else:
> +            self.show_history = False
> +            self.last_index = 0
> +            return cast(Optional[str], super().keypress(size, key))
> +        return None
> +
> +
> +class EditorWidget(urwid.Filler):
> +    """
> +    The Editor is a flow widget and has to wrapped inside a box widget.
> +    This class wraps the Editor inside filler widget.
> +    """
> +    def __init__(self, master: App) -> None:
> +        super().__init__(Editor(master), valign='top')
> +
> +
> +class HistoryBox(urwid.ListBox):
> +    """
> +    This widget is modelled using the ListBox widget, contains the list of
> +    all messages both QMP messages and log messsages to be shown in the
> TUI.
> +
> +    The messages are urwid.Text widgets. On every append of a message, the
> +    focus is shifted to the last appended message.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes the historybox widget
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        self.master = master
> +        self.history = urwid.SimpleFocusListWalker([])
> +        super().__init__(self.history)
> +
> +    def add_to_history(self, history: str) -> None:
> +        """
> +        Appends a message to the list and set the focus to the last
> appended
> +        message.
> +
> +        :param history:
> +            The history item(message/event) to be appended to the list.
> +        """
> +        self.history.append(urwid.Text(history))
> +        if self.history:
> +            self.history.set_focus(len(self.history) - 1)
> +
> +
> +class HistoryWindow(urwid.Frame):
> +    """
> +    This window composes the HistoryBox and EditorWidget in a horizontal
> split.
> +    By default the first focus is given to the history box.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes this widget and its child widgets.
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        self.master = master
> +        self.editor_widget = EditorWidget(master)
> +        self.editor = urwid.LineBox(self.editor_widget)
> +        self.history = HistoryBox(master)
> +        self.body = urwid.Pile([('weight', 80, self.history),
> +                                ('weight', 20, self.editor)])
> +        super().__init__(self.body)
> +        urwid.connect_signal(self.master, UPDATE_MSG,
> self.cb_add_to_history)
> +
> +    def cb_add_to_history(self, msg: str, level: Optional[str] = None) ->
> None:
> +        """
> +        Appends a message to the history box
> +
> +        :param msg:
> +            The message to be appended to the history box.
> +        """
> +        if level:
> +            msg = f'[{level}]: {msg}'
> +        self.history.add_to_history(msg)
> +
> +
> +class Window(urwid.Frame):
> +    """
> +    This window is the top most widget of the TUI and will contain other
> +    windows. Each window is responsible for displaying a specific
> +    functionality.
> +    For eg: The history window is responsible for showing the history of
> +    messages and the editor.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes this widget and its child windows.
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        self.master = master
> +        footer = StatusBar()
> +        body = HistoryWindow(master)
> +        super().__init__(body, footer=footer)
> +
> +
> +class TUILogHandler(Handler):
> +    """
> +    This handler routes all the log messages to the TUI screen.
> +    It is installed to the root logger to so that the log message from all
> +    libraries begin used is routed to the screen.
> +    """
> +    def __init__(self, tui: App) -> None:
> +        """
> +        Initializes the handler class.
> +
> +        :param tui:
> +            Reference to the TUI object.
> +        """
> +        super().__init__()
> +        self.tui = tui
> +
> +    def emit(self, record: LogRecord) -> None:
> +        """
> +        Emits a record to the TUI screen.
> +
> +        Appends the log message to the TUI screen
> +        """
> +        level = record.levelname
> +        msg = record.getMessage()
> +        self.tui.add_to_history(msg, level)
> +
> +
> +def main() -> None:
> +    """
> +    Driver of the whole script, parses arguments, initialize the TUI and
> +    the logger.
> +    """
> +    parser = argparse.ArgumentParser(description='AQMP TUI')
> +    parser.add_argument('qmp_server', help='Address of the QMP server. '
> +                        'Format <UNIX socket path | TCP addr:port>')
> +    parser.add_argument('--log-file', help='The Log file name')
> +    parser.add_argument('--log-level', default='WARNING',
> +                        help='Log level
> <CRITICAL|ERROR|WARNING|INFO|DEBUG|>')
> +    parser.add_argument('--asyncio-debug', action='store_true',
> +                        help='Enable debug mode for asyncio loop. '
> +                        'Generates lot of output, makes TUI unusable when
> '
> +                        'logs are logged in the TUI. '
> +                        'Use only when logging to a file.')
> +    args = parser.parse_args()
> +
> +    try:
> +        address = QEMUMonitorProtocol.parse_address(args.qmp_server)
> +    except QMPBadPortError as err:
> +        parser.error(str(err))
> +
> +    app = App(address)
> +
> +    root_logger = logging.getLogger()
> +    root_logger.setLevel(logging.getLevelName(args.log_level))
> +
> +    if args.log_file:
> +        root_logger.addHandler(logging.FileHandler(args.log_file))
> +    else:
> +        root_logger.addHandler(TUILogHandler(app))
> +
> +    app.run(args.asyncio_debug)
> +
> +
> +if __name__ == '__main__':
> +    main()
> diff --git a/python/setup.cfg b/python/setup.cfg
> index a0ed3279d8..1ff2b907a2 100644
> --- a/python/setup.cfg
> +++ b/python/setup.cfg
> @@ -81,8 +81,19 @@ namespace_packages = True
>  # fusepy has no type stubs:
>  allow_subclassing_any = True
>
> +[mypy-qemu.aqmp.aqmp_tui]
> +# urwid and urwid_readline have no type stubs:
> +allow_subclassing_any = True
> +
> +# The following missing import directives are because these libraries do
> not
> +# provide type stubs. Allow them on an as-needed basis for mypy.
>  [mypy-fuse]
> -# fusepy has no type stubs:
> +ignore_missing_imports = True
> +
> +[mypy-urwid]
> +ignore_missing_imports = True
> +
> +[mypy-urwid_readline]
>  ignore_missing_imports = True
>
>  [pylint.messages control]
> @@ -97,7 +108,7 @@ ignore_missing_imports = True
>  # --disable=W".
>  disable=too-many-function-args,  # mypy handles this with less false
> positives.
>          no-member,  # mypy also handles this better.
> -        missing-docstring, # FIXME
> +        # missing-docstring, # FIXME
>

^ Once patch #1 is removed, this stuff should also go.


>          fixme, # FIXME
>
>  [pylint.basic]
> --
> 2.17.1
>

[-- Attachment #2: Type: text/html, Size: 29881 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 0/7] AQMP TUI Draft
  2021-08-21  4:09 ` [PATCH v4 0/7] AQMP TUI Draft John Snow
@ 2021-08-21 21:20   ` Niteesh G. S.
  0 siblings, 0 replies; 15+ messages in thread
From: Niteesh G. S. @ 2021-08-21 21:20 UTC (permalink / raw)
  To: John Snow
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 2250 bytes --]

On Sat, Aug 21, 2021 at 9:39 AM John Snow <jsnow@redhat.com> wrote:

>
>
> On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
> wrote:
>
>> Hello all,
>>
>> Gitlab:
>> https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v4
>> CI: https://gitlab.com/niteesh.gs/qemu/-/pipelines/356024270
>>
>> Revision since v3:
>> 1) Added docstrings
>> 2) Minor changes in AQMP TUI Draft
>> 3) Switched to constant retry delay in QMP connection manager and other
>>    minor changes.
>>
>> G S Niteesh Babu (7):
>>   python: disable pylint errors for aqmp-tui
>>   python: Add dependencies for AQMP TUI
>>   python/aqmp-tui: Add AQMP TUI draft
>>   python: Add entry point for aqmp-tui
>>   python: add optional pygments dependency
>>   python/aqmp-tui: Add syntax highlighting
>>   python/aqmp-tui: Add QMP connection manager
>>
>>  python/Pipfile.lock          |  20 +
>>  python/qemu/aqmp/aqmp_tui.py | 681 +++++++++++++++++++++++++++++++++++
>>  python/setup.cfg             |  29 +-
>>  3 files changed, 729 insertions(+), 1 deletion(-)
>>  create mode 100644 python/qemu/aqmp/aqmp_tui.py
>>
>> --
>> 2.17.1
>>
>>
> Hiya, please specify what your branch is based on when you submit your
> patchsets using the Based-On tag.
>
Oops sorry, I'll make sure to add it in the next revision.

>
> - It's time to drop patch #1 entirely.
>
- We can drop the word 'draft' from the commit messages now, let's try to
> make this solid.
>
- If you want to keep the TODO comments in the code, add a pylint
> configuration item that allows "todo" but disallows "fixme" and "xxx"
> comments.
>

> Detailed review to follow tomorrow, but you can start working on these
> items right away. I might also squash patch #7 directly into patch #3, but
> haven't looked too closely yet.
>
I have addressed all your above comments in this branch
https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v5
except squashing of patches #3 and #7. Will do it once you review patch #7.

>
> (Note that due to an update to pylint that happened just today, check-tox
> is going to fail now -- that's fine, it's not your fault. As long as
> check-pipenv works, you're in good shape. I'll have a fix in my python
> branch tomorrow for these problems.)
>

[-- Attachment #2: Type: text/html, Size: 4772 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft
  2021-08-21 20:05   ` John Snow
@ 2021-08-21 22:21     ` Niteesh G. S.
  0 siblings, 0 replies; 15+ messages in thread
From: Niteesh G. S. @ 2021-08-21 22:21 UTC (permalink / raw)
  To: John Snow
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 23880 bytes --]

On Sun, Aug 22, 2021 at 1:36 AM John Snow <jsnow@redhat.com> wrote:

> On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
> wrote:
>
>> Added a draft of AQMP TUI.
>>
>> Implements the follwing basic features:
>> 1) Command transmission/reception.
>> 2) Shows events asynchronously.
>> 3) Shows server status in the bottom status bar.
>>
>> Also added type annotations and necessary pylint,
>> mypy configurations
>>
>> Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
>> ---
>>  python/qemu/aqmp/aqmp_tui.py | 566 +++++++++++++++++++++++++++++++++++
>>  python/setup.cfg             |  15 +-
>>  2 files changed, 579 insertions(+), 2 deletions(-)
>>  create mode 100644 python/qemu/aqmp/aqmp_tui.py
>>
>> diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
>> new file mode 100644
>> index 0000000000..12c9c4162a
>> --- /dev/null
>> +++ b/python/qemu/aqmp/aqmp_tui.py
>> @@ -0,0 +1,566 @@
>> +# Copyright (c) 2021
>> +#
>> +# Authors:
>> +#  Niteesh Babu G S <niteesh.gs@gmail.com>
>> +#
>> +# This work is licensed under the terms of the GNU GPL, version 2 or
>> +# later.  See the COPYING file in the top-level directory.
>> +"""
>> +AQMP TUI
>> +
>> +AQMP TUI is an asynchronous interface built on top the of the AQMP
>> library.
>> +It is the successor of QMP-shell and is bought-in as a replacement for
>> it.
>> +
>> +Example Usage: aqmp-tui <SOCKET | TCP IP:PORT>
>> +Full Usage: aqmp-tui --help
>> +"""
>> +
>> +import argparse
>> +import asyncio
>> +import logging
>> +from logging import Handler, LogRecord
>> +import signal
>> +from typing import (
>> +    List,
>> +    Optional,
>> +    Tuple,
>> +    Type,
>> +    Union,
>> +    cast,
>> +)
>> +
>> +import urwid
>> +import urwid_readline
>> +
>> +from ..qmp import QEMUMonitorProtocol, QMPBadPortError
>> +from .message import DeserializationError, Message, UnexpectedTypeError
>> +from .protocol import ConnectError
>> +from .qmp_client import ExecInterruptedError, QMPClient
>> +from .util import create_task, pretty_traceback
>> +
>> +
>> +# The name of the signal that is used to update the history list
>> +UPDATE_MSG: str = 'UPDATE_MSG'
>> +
>> +
>> +def format_json(msg: str) -> str:
>> +    """
>> +    Formats given multi-line JSON message into a single-line message.
>> +    Converting into single line is more asthetically pleasing when
>> looking
>> +    along with error messages.
>> +
>> +    Eg:
>> +    Input:
>> +          [ 1,
>> +            true,
>> +            3 ]
>> +    The above input is not a valid QMP message and produces the
>> following error
>> +    "QMP message is not a JSON object."
>> +    When displaying this in TUI in multiline mode we get
>> +
>> +        [ 1,
>> +          true,
>> +          3 ]: QMP message is not a JSON object.
>> +
>> +    whereas in singleline mode we get the following
>> +
>> +        [1, true, 3]: QMP message is not a JSON object.
>> +
>> +    The single line mode is more asthetically pleasing.
>> +
>> +    :param msg:
>> +        The message to formatted into single line.
>> +
>> +    :return: Formatted singleline message.
>> +
>> +    NOTE: We cannot use the JSON module here because it is only capable
>> of
>> +    format valid JSON messages. But here the goal is to also format
>> invalid
>> +    JSON messages.
>> +    """
>> +    msg = msg.replace('\n', '')
>> +    words = msg.split(' ')
>> +    words = [word for word in words if word != '']
>> +    return ' '.join(words)
>> +
>> +
>> +def has_tui_handler(logger: logging.Logger,
>> +                    handler_type: Type[Handler]) -> bool:
>> +    """
>> +    The Logger class has no interface to check if a certain type of
>> handler is
>> +    installed or not. So we provide an interface to do so.
>> +
>> +    :param logger:
>> +        Logger object
>> +    :param handler_type:
>> +        The type of the handler to be checked.
>> +
>> +    :return: returns True if handler of type `handler_type` is installed
>> else
>> +             False.
>> +    """
>> +    handlers = logger.handlers
>> +    for handler in handlers:
>> +        if isinstance(handler, handler_type):
>> +            return True
>> +    return False
>> +
>> +
>> +class App(QMPClient):
>> +    """
>> +    Implements the AQMP TUI.
>> +
>> +    Initializes the widgets and starts the urwid event loop.
>> +    """
>> +    def __init__(self, address: Union[str, Tuple[str, int]]) -> None:
>> +        """
>> +        Initializes the TUI.
>> +
>> +        :param address:
>> +            Address of the server to connect to.
>> +        """
>> +        urwid.register_signal(type(self), UPDATE_MSG)
>> +        self.window = Window(self)
>> +        self.address = address
>> +        self.aloop: Optional[asyncio.AbstractEventLoop] = None
>> +        super().__init__()
>> +
>> +    def add_to_history(self, msg: str, level: Optional[str] = None) ->
>> None:
>> +        """
>> +        Appends the msg to the history list.
>> +
>> +        :param msg:
>> +            The raw message to be appended in string type.
>> +        """
>> +        urwid.emit_signal(self, UPDATE_MSG, msg, level)
>> +
>> +    def _cb_outbound(self, msg: Message) -> Message:
>> +        """
>> +        Callback: outbound message hook.
>> +
>> +        Appends the outgoing messages to the history box.
>> +
>> +        :param msg: raw outbound message.
>> +        :return: final outbound message.
>> +        """
>> +        str_msg = str(msg)
>> +
>> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
>> +            logging.debug('Request: %s', str_msg)
>> +        self.add_to_history('<-- ' + str_msg)
>> +        return msg
>> +
>> +    def _cb_inbound(self, msg: Message) -> Message:
>> +        """
>> +        Callback: outbound message hook.
>> +
>> +        Appends the incoming messages to the history box.
>> +
>> +        :param msg: raw inbound message.
>> +        :return: final inbound message.
>> +        """
>> +        str_msg = str(msg)
>> +
>> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
>> +            logging.debug('Request: %s', str_msg)
>> +        self.add_to_history('--> ' + str_msg)
>> +        return msg
>> +
>>
>
> Starting here: ...
>
>
>> +    def handle_event(self, event: Message) -> None:
>> +        """
>> +        Handles the event.
>> +
>> +        :param event:
>> +            The event to be handled.
>> +        """
>> +        # TODO: Consider all states present in qapi/run-state.json
>> +        if event['event'] == 'SHUTDOWN':
>> +            self._set_status('[Server Shutdown]')
>> +
>> +    async def wait_for_events(self) -> None:
>> +        """
>> +        This coroutine continously waits for events and dispatches them.
>> +        """
>> +        async for event in self.events:
>> +            self.handle_event(event)
>> +
>>
>
> ... until here, we can remove these from this series, because we don't use
> them for anything by the end of this series. We can re-add them once that
> "TODO" is done.
>
I have removed this in the upcoming revision.

>
>
>> +    async def _send_to_server(self, msg: Message) -> None:
>> +        """
>> +        This coroutine sends the message to the server.
>> +        The message has to be pre-validated.
>> +
>> +        :param msg:
>> +            Pre-validated message to be to sent to the server.
>> +
>> +        :raise Exception: When an unhandled exception is caught.
>> +        """
>> +        try:
>> +            await self._raw(msg, assign_id='id' not in msg)
>> +        except ExecInterruptedError:
>> +            logging.info('Error server disconnected before reply')
>> +            self.add_to_history('Server disconnected before reply',
>> 'ERROR')
>> +            self._set_status("[Server Disconnected]")
>> +        except Exception as err:
>> +            logging.error('Exception from _send_to_server: %s', str(err))
>> +            raise err
>> +
>> +    def cb_send_to_server(self, raw_msg: str) -> None:
>> +        """
>> +        Validates and sends the message to the server.
>> +        The raw string message is first converted into a Message object
>> +        and is then sent to the server.
>> +
>> +        :param raw_msg:
>> +            The raw string message to be sent to the server.
>> +
>> +        :raise Exception: When an unhandled exception is caught.
>> +        """
>> +        try:
>> +            raw_msg = format_json(raw_msg)
>> +            msg = Message(bytes(raw_msg, encoding='utf-8'))
>> +            create_task(self._send_to_server(msg))
>> +        except (ValueError, TypeError) as err:
>> +            logging.info('Invalid message: %s', str(err))
>> +            self.add_to_history(f'{raw_msg}: {err}')
>> +        except (DeserializationError, UnexpectedTypeError) as err:
>> +            logging.info('Invalid message: %s', err.error_message)
>> +            self.add_to_history(f'{raw_msg}: {err.error_message}')
>> +
>> +    def unhandled_input(self, key: str) -> None:
>> +        """
>> +        Handle's keys which haven't been handled by the child widgets.
>> +
>> +        :param key:
>> +            Unhandled key
>> +        """
>> +        if key == 'esc':
>> +            self.kill_app()
>> +
>> +    def kill_app(self) -> None:
>> +        """
>> +        Initiates killing of app. A bridge between asynchronous and
>> synchronous
>> +        code.
>> +        """
>> +        create_task(self._kill_app())
>> +
>> +    async def _kill_app(self) -> None:
>> +        """
>> +        This coroutine initiates the actual disconnect process and calls
>> +        urwid.ExitMainLoop() to kill the TUI.
>> +
>> +        :raise Exception: When an unhandled exception is caught.
>> +        """
>> +        # It is ok to call disconnect even in disconnect state
>> +        try:
>> +            await self.disconnect()
>> +            logging.debug('Disconnect finished. Exiting app')
>> +        except EOFError:
>> +            # We receive an EOF during disconnect, ignore that
>> +            pass
>> +        except Exception as err:
>> +            logging.info('_kill_app: %s', str(err))
>> +            # Let the app crash after providing a proper stack trace
>> +            raise err
>> +        raise urwid.ExitMainLoop()
>> +
>> +    def _set_status(self, msg: str) -> None:
>> +        """
>> +        Sets the message as the status.
>> +
>> +        :param msg:
>> +            The message to be displayed in the status bar.
>> +        """
>> +        self.window.footer.set_text(msg)
>> +
>> +    def _get_formatted_address(self) -> str:
>> +        """
>> +        Returns a formatted version of the server's address.
>> +
>> +        :return: formatted address
>> +        """
>> +        if isinstance(self.address, tuple):
>> +            host, port = self.address
>> +            addr = f'{host}:{port}'
>> +        else:
>> +            addr = f'{self.address}'
>> +        return addr
>> +
>> +    async def connect_server(self) -> None:
>> +        """
>> +        Initiates a connection to the server at address `self.address`
>> +        and in case of a failure, sets the status to the respective
>> error.
>> +        """
>> +        try:
>> +            await self.connect(self.address)
>> +            addr = self._get_formatted_address()
>> +            self._set_status(f'Connected to {addr}')
>> +        except ConnectError as err:
>> +            logging.info('connect_server: ConnectError %s', str(err))
>> +            self._set_status(f'[ConnectError: {err.error_message}]')
>> +
>> +    def run(self, debug: bool = False) -> None:
>> +        """
>> +        Starts the long running co-routines and the urwid event loop.
>> +
>> +        :param debug:
>> +            Enables/Disables asyncio event loop debugging
>> +        """
>> +        self.aloop = asyncio.get_event_loop()
>> +        self.aloop.set_debug(debug)
>> +
>> +        # Gracefully handle SIGTERM and SIGINT signals
>> +        cancel_signals = [signal.SIGTERM, signal.SIGINT]
>> +        for sig in cancel_signals:
>> +            self.aloop.add_signal_handler(sig, self.kill_app)
>> +
>> +        event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
>> +        main_loop = urwid.MainLoop(urwid.AttrMap(self.window,
>> 'background'),
>> +                                   unhandled_input=self.unhandled_input,
>> +                                   handle_mouse=True,
>> +                                   event_loop=event_loop)
>> +
>> +        create_task(self.wait_for_events(), self.aloop)
>>
>
> This can be removed since it isn't used for anything by the end of this
> series. We can re-add the event watcher when the status updater is actually
> completed.
>
Removed.

>
>
>> +        create_task(self.connect_server(), self.aloop)
>> +        try:
>> +            main_loop.run()
>> +        except Exception as err:
>> +            logging.error('%s\n%s\n', str(err), pretty_traceback())
>> +            raise err
>> +
>> +
>> +class StatusBar(urwid.Text):
>> +    """
>> +    A simple statusbar modelled using the Text widget. The status can be
>> +    set using the set_text function. All text set is aligned to right.
>> +    """
>> +    def __init__(self, text: str = ''):
>> +        super().__init__(text, align='right')
>> +
>> +
>> +class Editor(urwid_readline.ReadlineEdit):
>> +    """
>> +    A simple editor modelled using the urwid_readline.ReadlineEdit
>> widget.
>> +    Mimcs GNU readline shortcuts and provides history support.
>> +
>> +    The readline shortcuts can be found below:
>> +    https://github.com/rr-/urwid_readline#features
>> +
>> +    Along with the readline features, this editor also has support for
>> +    history. Pressing the 'up' arrow key with empty message box, lists
>> the
>> +    previous message inplace.
>> +
>> +    Currently there is no support to save the history to a file. The
>> history of
>> +    previous commands is lost on exit.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes the editor widget
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        super().__init__(caption='> ', multiline=True)
>> +        self.master = master
>> +        self.history: List[str] = []
>> +        self.last_index: int = -1
>> +        self.show_history: bool = False
>> +
>> +    def keypress(self, size: Tuple[int, int], key: str) -> Optional[str]:
>> +        """
>> +        Handles the keypress on this widget.
>> +
>> +        :param size:
>> +            The current size of the widget.
>> +        :param key:
>> +            The key to be handled.
>> +
>> +        :return: Unhandled key if any.
>> +        """
>> +        # TODO: Add some logic for down key and clean up logic if
>> possible.
>>
>
> What logic needs to be added here? Can this comment be made more explicit?
> What kind of cleanup do we need to do here, still?
> (Is now the right time to do that cleanup, or not?)
>
> If you want to leave the TODO in, then edit setup.cfg and add the
> exemption for it.
>
I have cleaned the logic as much as I can and have also added support for
the down key to go up the history stack.
So this TODO will be removed in the upcoming revision.

>
>
>> +        # Returning None means the key has been handled by this widget
>> +        # which otherwise is propogated to the parent widget to be
>> +        # handled
>> +        msg = self.get_edit_text()
>> +        if key == 'up' and not msg:
>> +            # Show the history when 'up arrow' is pressed with no input
>> text.
>> +            # NOTE: The show_history logic is necessary because in
>> 'multiline'
>> +            # mode (which we use) 'up arrow' is used to move between
>> lines.
>> +            self.show_history = True
>> +            last_msg = self.history[self.last_index] if self.history
>> else ''
>> +            self.set_edit_text(last_msg)
>> +            self.edit_pos = len(last_msg)
>> +            self.last_index += 1
>> +        elif key == 'up' and self.show_history:
>> +            if self.last_index < len(self.history):
>> +                self.set_edit_text(self.history[self.last_index])
>> +                self.edit_pos = len(self.history[self.last_index])
>> +                self.last_index += 1
>> +        elif key == 'meta enter':
>> +            # When using multiline, enter inserts a new line into the
>> editor
>> +            # send the input to the server on alt + enter
>> +            self.master.cb_send_to_server(msg)
>> +            self.history.insert(0, msg)
>> +            self.set_edit_text('')
>> +            self.last_index = 0
>> +            self.show_history = False
>> +        else:
>> +            self.show_history = False
>> +            self.last_index = 0
>> +            return cast(Optional[str], super().keypress(size, key))
>> +        return None
>> +
>> +
>> +class EditorWidget(urwid.Filler):
>> +    """
>> +    The Editor is a flow widget and has to wrapped inside a box widget.
>> +    This class wraps the Editor inside filler widget.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        super().__init__(Editor(master), valign='top')
>> +
>> +
>> +class HistoryBox(urwid.ListBox):
>> +    """
>> +    This widget is modelled using the ListBox widget, contains the list
>> of
>> +    all messages both QMP messages and log messsages to be shown in the
>> TUI.
>> +
>> +    The messages are urwid.Text widgets. On every append of a message,
>> the
>> +    focus is shifted to the last appended message.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes the historybox widget
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        self.master = master
>> +        self.history = urwid.SimpleFocusListWalker([])
>> +        super().__init__(self.history)
>> +
>> +    def add_to_history(self, history: str) -> None:
>> +        """
>> +        Appends a message to the list and set the focus to the last
>> appended
>> +        message.
>> +
>> +        :param history:
>> +            The history item(message/event) to be appended to the list.
>> +        """
>> +        self.history.append(urwid.Text(history))
>> +        if self.history:
>> +            self.history.set_focus(len(self.history) - 1)
>> +
>> +
>> +class HistoryWindow(urwid.Frame):
>> +    """
>> +    This window composes the HistoryBox and EditorWidget in a horizontal
>> split.
>> +    By default the first focus is given to the history box.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes this widget and its child widgets.
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        self.master = master
>> +        self.editor_widget = EditorWidget(master)
>> +        self.editor = urwid.LineBox(self.editor_widget)
>> +        self.history = HistoryBox(master)
>> +        self.body = urwid.Pile([('weight', 80, self.history),
>> +                                ('weight', 20, self.editor)])
>> +        super().__init__(self.body)
>> +        urwid.connect_signal(self.master, UPDATE_MSG,
>> self.cb_add_to_history)
>> +
>> +    def cb_add_to_history(self, msg: str, level: Optional[str] = None)
>> -> None:
>> +        """
>> +        Appends a message to the history box
>> +
>> +        :param msg:
>> +            The message to be appended to the history box.
>> +        """
>> +        if level:
>> +            msg = f'[{level}]: {msg}'
>> +        self.history.add_to_history(msg)
>> +
>> +
>> +class Window(urwid.Frame):
>> +    """
>> +    This window is the top most widget of the TUI and will contain other
>> +    windows. Each window is responsible for displaying a specific
>> +    functionality.
>> +    For eg: The history window is responsible for showing the history of
>> +    messages and the editor.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes this widget and its child windows.
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        self.master = master
>> +        footer = StatusBar()
>> +        body = HistoryWindow(master)
>> +        super().__init__(body, footer=footer)
>> +
>> +
>> +class TUILogHandler(Handler):
>> +    """
>> +    This handler routes all the log messages to the TUI screen.
>> +    It is installed to the root logger to so that the log message from
>> all
>> +    libraries begin used is routed to the screen.
>> +    """
>> +    def __init__(self, tui: App) -> None:
>> +        """
>> +        Initializes the handler class.
>> +
>> +        :param tui:
>> +            Reference to the TUI object.
>> +        """
>> +        super().__init__()
>> +        self.tui = tui
>> +
>> +    def emit(self, record: LogRecord) -> None:
>> +        """
>> +        Emits a record to the TUI screen.
>> +
>> +        Appends the log message to the TUI screen
>> +        """
>> +        level = record.levelname
>> +        msg = record.getMessage()
>> +        self.tui.add_to_history(msg, level)
>> +
>> +
>> +def main() -> None:
>> +    """
>> +    Driver of the whole script, parses arguments, initialize the TUI and
>> +    the logger.
>> +    """
>> +    parser = argparse.ArgumentParser(description='AQMP TUI')
>> +    parser.add_argument('qmp_server', help='Address of the QMP server. '
>> +                        'Format <UNIX socket path | TCP addr:port>')
>> +    parser.add_argument('--log-file', help='The Log file name')
>> +    parser.add_argument('--log-level', default='WARNING',
>> +                        help='Log level
>> <CRITICAL|ERROR|WARNING|INFO|DEBUG|>')
>> +    parser.add_argument('--asyncio-debug', action='store_true',
>> +                        help='Enable debug mode for asyncio loop. '
>> +                        'Generates lot of output, makes TUI unusable
>> when '
>> +                        'logs are logged in the TUI. '
>> +                        'Use only when logging to a file.')
>> +    args = parser.parse_args()
>> +
>> +    try:
>> +        address = QEMUMonitorProtocol.parse_address(args.qmp_server)
>> +    except QMPBadPortError as err:
>> +        parser.error(str(err))
>> +
>> +    app = App(address)
>> +
>> +    root_logger = logging.getLogger()
>> +    root_logger.setLevel(logging.getLevelName(args.log_level))
>> +
>> +    if args.log_file:
>> +        root_logger.addHandler(logging.FileHandler(args.log_file))
>> +    else:
>> +        root_logger.addHandler(TUILogHandler(app))
>> +
>> +    app.run(args.asyncio_debug)
>> +
>> +
>> +if __name__ == '__main__':
>> +    main()
>> diff --git a/python/setup.cfg b/python/setup.cfg
>> index a0ed3279d8..1ff2b907a2 100644
>> --- a/python/setup.cfg
>> +++ b/python/setup.cfg
>> @@ -81,8 +81,19 @@ namespace_packages = True
>>  # fusepy has no type stubs:
>>  allow_subclassing_any = True
>>
>> +[mypy-qemu.aqmp.aqmp_tui]
>> +# urwid and urwid_readline have no type stubs:
>> +allow_subclassing_any = True
>> +
>> +# The following missing import directives are because these libraries do
>> not
>> +# provide type stubs. Allow them on an as-needed basis for mypy.
>>  [mypy-fuse]
>> -# fusepy has no type stubs:
>> +ignore_missing_imports = True
>> +
>> +[mypy-urwid]
>> +ignore_missing_imports = True
>> +
>> +[mypy-urwid_readline]
>>  ignore_missing_imports = True
>>
>>  [pylint.messages control]
>> @@ -97,7 +108,7 @@ ignore_missing_imports = True
>>  # --disable=W".
>>  disable=too-many-function-args,  # mypy handles this with less false
>> positives.
>>          no-member,  # mypy also handles this better.
>> -        missing-docstring, # FIXME
>> +        # missing-docstring, # FIXME
>>
>
> ^ Once patch #1 is removed, this stuff should also go.
>
Removed.

>
>
>>          fixme, # FIXME
>>
>>  [pylint.basic]
>> --
>> 2.17.1
>>
>
>

[-- Attachment #2: Type: text/html, Size: 31699 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft
  2021-08-19 17:38 ` [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft G S Niteesh Babu
  2021-08-21 20:05   ` John Snow
@ 2021-08-22  7:33   ` John Snow
  2021-08-23 10:37     ` Niteesh G. S.
  1 sibling, 1 reply; 15+ messages in thread
From: John Snow @ 2021-08-22  7:33 UTC (permalink / raw)
  To: G S Niteesh Babu
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 22751 bytes --]

On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
wrote:

> Added a draft of AQMP TUI.
>
> Implements the follwing basic features:
> 1) Command transmission/reception.
> 2) Shows events asynchronously.
> 3) Shows server status in the bottom status bar.
>
> Also added type annotations and necessary pylint,
> mypy configurations
>
> Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
> ---
>  python/qemu/aqmp/aqmp_tui.py | 566 +++++++++++++++++++++++++++++++++++
>  python/setup.cfg             |  15 +-
>  2 files changed, 579 insertions(+), 2 deletions(-)
>  create mode 100644 python/qemu/aqmp/aqmp_tui.py
>
> diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
> new file mode 100644
> index 0000000000..12c9c4162a
> --- /dev/null
> +++ b/python/qemu/aqmp/aqmp_tui.py
> @@ -0,0 +1,566 @@
> +# Copyright (c) 2021
> +#
> +# Authors:
> +#  Niteesh Babu G S <niteesh.gs@gmail.com>
> +#
> +# This work is licensed under the terms of the GNU GPL, version 2 or
> +# later.  See the COPYING file in the top-level directory.
> +"""
> +AQMP TUI
> +
> +AQMP TUI is an asynchronous interface built on top the of the AQMP
> library.
> +It is the successor of QMP-shell and is bought-in as a replacement for it.
> +
> +Example Usage: aqmp-tui <SOCKET | TCP IP:PORT>
> +Full Usage: aqmp-tui --help
> +"""
> +
> +import argparse
> +import asyncio
> +import logging
> +from logging import Handler, LogRecord
> +import signal
> +from typing import (
> +    List,
> +    Optional,
> +    Tuple,
> +    Type,
> +    Union,
> +    cast,
> +)
> +
> +import urwid
> +import urwid_readline
> +
> +from ..qmp import QEMUMonitorProtocol, QMPBadPortError
> +from .message import DeserializationError, Message, UnexpectedTypeError
> +from .protocol import ConnectError
> +from .qmp_client import ExecInterruptedError, QMPClient
> +from .util import create_task, pretty_traceback
> +
> +
> +# The name of the signal that is used to update the history list
> +UPDATE_MSG: str = 'UPDATE_MSG'
> +
> +
> +def format_json(msg: str) -> str:
> +    """
> +    Formats given multi-line JSON message into a single-line message.
> +    Converting into single line is more asthetically pleasing when looking
> +    along with error messages.
> +
> +    Eg:
> +    Input:
> +          [ 1,
> +            true,
> +            3 ]
> +    The above input is not a valid QMP message and produces the following
> error
> +    "QMP message is not a JSON object."
> +    When displaying this in TUI in multiline mode we get
> +
> +        [ 1,
> +          true,
> +          3 ]: QMP message is not a JSON object.
> +
> +    whereas in singleline mode we get the following
> +
> +        [1, true, 3]: QMP message is not a JSON object.
> +
> +    The single line mode is more asthetically pleasing.
> +
> +    :param msg:
> +        The message to formatted into single line.
> +
> +    :return: Formatted singleline message.
> +
> +    NOTE: We cannot use the JSON module here because it is only capable of
> +    format valid JSON messages. But here the goal is to also format
> invalid
> +    JSON messages.
> +    """
> +    msg = msg.replace('\n', '')
> +    words = msg.split(' ')
> +    words = [word for word in words if word != '']
> +    return ' '.join(words)
> +
> +
> +def has_tui_handler(logger: logging.Logger,
> +                    handler_type: Type[Handler]) -> bool:
> +    """
> +    The Logger class has no interface to check if a certain type of
> handler is
> +    installed or not. So we provide an interface to do so.
> +
> +    :param logger:
> +        Logger object
> +    :param handler_type:
> +        The type of the handler to be checked.
> +
> +    :return: returns True if handler of type `handler_type` is installed
> else
> +             False.
> +    """
> +    handlers = logger.handlers
> +    for handler in handlers:
> +        if isinstance(handler, handler_type):
> +            return True
> +    return False
> +
> +
> +class App(QMPClient):
> +    """
> +    Implements the AQMP TUI.
> +
> +    Initializes the widgets and starts the urwid event loop.
> +    """
> +    def __init__(self, address: Union[str, Tuple[str, int]]) -> None:
> +        """
> +        Initializes the TUI.
> +
> +        :param address:
> +            Address of the server to connect to.
> +        """
> +        urwid.register_signal(type(self), UPDATE_MSG)
> +        self.window = Window(self)
> +        self.address = address
> +        self.aloop: Optional[asyncio.AbstractEventLoop] = None
> +        super().__init__()
> +
> +    def add_to_history(self, msg: str, level: Optional[str] = None) ->
> None:
> +        """
> +        Appends the msg to the history list.
> +
> +        :param msg:
> +            The raw message to be appended in string type.
> +        """
> +        urwid.emit_signal(self, UPDATE_MSG, msg, level)
> +
> +    def _cb_outbound(self, msg: Message) -> Message:
> +        """
> +        Callback: outbound message hook.
> +
> +        Appends the outgoing messages to the history box.
> +
> +        :param msg: raw outbound message.
> +        :return: final outbound message.
> +        """
> +        str_msg = str(msg)
> +
> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
> +            logging.debug('Request: %s', str_msg)
> +        self.add_to_history('<-- ' + str_msg)
> +        return msg
> +
> +    def _cb_inbound(self, msg: Message) -> Message:
> +        """
> +        Callback: outbound message hook.
> +
> +        Appends the incoming messages to the history box.
> +
> +        :param msg: raw inbound message.
> +        :return: final inbound message.
> +        """
> +        str_msg = str(msg)
> +
> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
> +            logging.debug('Request: %s', str_msg)
> +        self.add_to_history('--> ' + str_msg)
> +        return msg
> +
> +    def handle_event(self, event: Message) -> None:
> +        """
> +        Handles the event.
> +
> +        :param event:
> +            The event to be handled.
> +        """
> +        # TODO: Consider all states present in qapi/run-state.json
> +        if event['event'] == 'SHUTDOWN':
> +            self._set_status('[Server Shutdown]')
> +
> +    async def wait_for_events(self) -> None:
> +        """
> +        This coroutine continously waits for events and dispatches them.
> +        """
> +        async for event in self.events:
> +            self.handle_event(event)
> +
> +    async def _send_to_server(self, msg: Message) -> None:
> +        """
> +        This coroutine sends the message to the server.
> +        The message has to be pre-validated.
> +
> +        :param msg:
> +            Pre-validated message to be to sent to the server.
> +
> +        :raise Exception: When an unhandled exception is caught.
> +        """
> +        try:
> +            await self._raw(msg, assign_id='id' not in msg)
> +        except ExecInterruptedError:
> +            logging.info('Error server disconnected before reply')
> +            self.add_to_history('Server disconnected before reply',
> 'ERROR')
> +            self._set_status("[Server Disconnected]")
> +        except Exception as err:
> +            logging.error('Exception from _send_to_server: %s', str(err))
> +            raise err
> +
> +    def cb_send_to_server(self, raw_msg: str) -> None:
> +        """
> +        Validates and sends the message to the server.
> +        The raw string message is first converted into a Message object
> +        and is then sent to the server.
> +
> +        :param raw_msg:
> +            The raw string message to be sent to the server.
> +
> +        :raise Exception: When an unhandled exception is caught.
> +        """
> +        try:
> +            raw_msg = format_json(raw_msg)
> +            msg = Message(bytes(raw_msg, encoding='utf-8'))
> +            create_task(self._send_to_server(msg))
> +        except (ValueError, TypeError) as err:
> +            logging.info('Invalid message: %s', str(err))
> +            self.add_to_history(f'{raw_msg}: {err}')
> +        except (DeserializationError, UnexpectedTypeError) as err:
> +            logging.info('Invalid message: %s', err.error_message)
> +            self.add_to_history(f'{raw_msg}: {err.error_message}')
> +
> +    def unhandled_input(self, key: str) -> None:
> +        """
> +        Handle's keys which haven't been handled by the child widgets.
> +
> +        :param key:
> +            Unhandled key
> +        """
> +        if key == 'esc':
> +            self.kill_app()
> +
> +    def kill_app(self) -> None:
> +        """
> +        Initiates killing of app. A bridge between asynchronous and
> synchronous
> +        code.
> +        """
> +        create_task(self._kill_app())
> +
> +    async def _kill_app(self) -> None:
> +        """
> +        This coroutine initiates the actual disconnect process and calls
> +        urwid.ExitMainLoop() to kill the TUI.
> +
> +        :raise Exception: When an unhandled exception is caught.
> +        """
> +        # It is ok to call disconnect even in disconnect state
> +        try:
> +            await self.disconnect()
> +            logging.debug('Disconnect finished. Exiting app')
> +        except EOFError:
> +            # We receive an EOF during disconnect, ignore that
> +            pass
> +        except Exception as err:
> +            logging.info('_kill_app: %s', str(err))
> +            # Let the app crash after providing a proper stack trace
> +            raise err
> +        raise urwid.ExitMainLoop()
> +
> +    def _set_status(self, msg: str) -> None:
> +        """
> +        Sets the message as the status.
> +
> +        :param msg:
> +            The message to be displayed in the status bar.
> +        """
> +        self.window.footer.set_text(msg)
> +
> +    def _get_formatted_address(self) -> str:
> +        """
> +        Returns a formatted version of the server's address.
> +
> +        :return: formatted address
> +        """
> +        if isinstance(self.address, tuple):
> +            host, port = self.address
> +            addr = f'{host}:{port}'
> +        else:
> +            addr = f'{self.address}'
> +        return addr
> +
> +    async def connect_server(self) -> None:
> +        """
> +        Initiates a connection to the server at address `self.address`
> +        and in case of a failure, sets the status to the respective error.
> +        """
> +        try:
> +            await self.connect(self.address)
> +            addr = self._get_formatted_address()
> +            self._set_status(f'Connected to {addr}')
> +        except ConnectError as err:
> +            logging.info('connect_server: ConnectError %s', str(err))
> +            self._set_status(f'[ConnectError: {err.error_message}]')
> +
> +    def run(self, debug: bool = False) -> None:
> +        """
> +        Starts the long running co-routines and the urwid event loop.
> +
> +        :param debug:
> +            Enables/Disables asyncio event loop debugging
> +        """
> +        self.aloop = asyncio.get_event_loop()
> +        self.aloop.set_debug(debug)
> +
> +        # Gracefully handle SIGTERM and SIGINT signals
> +        cancel_signals = [signal.SIGTERM, signal.SIGINT]
> +        for sig in cancel_signals:
> +            self.aloop.add_signal_handler(sig, self.kill_app)
> +
> +        event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
> +        main_loop = urwid.MainLoop(urwid.AttrMap(self.window,
> 'background'),
> +                                   unhandled_input=self.unhandled_input,
> +                                   handle_mouse=True,
> +                                   event_loop=event_loop)
> +
> +        create_task(self.wait_for_events(), self.aloop)
> +        create_task(self.connect_server(), self.aloop)
> +        try:
> +            main_loop.run()
> +        except Exception as err:
> +            logging.error('%s\n%s\n', str(err), pretty_traceback())
> +            raise err
> +
> +
> +class StatusBar(urwid.Text):
> +    """
> +    A simple statusbar modelled using the Text widget. The status can be
> +    set using the set_text function. All text set is aligned to right.
> +    """
> +    def __init__(self, text: str = ''):
> +        super().__init__(text, align='right')
> +
> +
> +class Editor(urwid_readline.ReadlineEdit):
> +    """
> +    A simple editor modelled using the urwid_readline.ReadlineEdit widget.
> +    Mimcs GNU readline shortcuts and provides history support.
> +
> +    The readline shortcuts can be found below:
> +    https://github.com/rr-/urwid_readline#features
> +
> +    Along with the readline features, this editor also has support for
> +    history. Pressing the 'up' arrow key with empty message box, lists the
> +    previous message inplace.
> +
> +    Currently there is no support to save the history to a file. The
> history of
> +    previous commands is lost on exit.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes the editor widget
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        super().__init__(caption='> ', multiline=True)
> +        self.master = master
> +        self.history: List[str] = []
> +        self.last_index: int = -1
> +        self.show_history: bool = False
> +
> +    def keypress(self, size: Tuple[int, int], key: str) -> Optional[str]:
> +        """
> +        Handles the keypress on this widget.
> +
> +        :param size:
> +            The current size of the widget.
> +        :param key:
> +            The key to be handled.
> +
> +        :return: Unhandled key if any.
> +        """
> +        # TODO: Add some logic for down key and clean up logic if
> possible.
> +        # Returning None means the key has been handled by this widget
> +        # which otherwise is propogated to the parent widget to be
> +        # handled
> +        msg = self.get_edit_text()
> +        if key == 'up' and not msg:
> +            # Show the history when 'up arrow' is pressed with no input
> text.
> +            # NOTE: The show_history logic is necessary because in
> 'multiline'
> +            # mode (which we use) 'up arrow' is used to move between
> lines.
> +            self.show_history = True
> +            last_msg = self.history[self.last_index] if self.history else
> ''
> +            self.set_edit_text(last_msg)
> +            self.edit_pos = len(last_msg)
> +            self.last_index += 1
> +        elif key == 'up' and self.show_history:
> +            if self.last_index < len(self.history):
> +                self.set_edit_text(self.history[self.last_index])
> +                self.edit_pos = len(self.history[self.last_index])
> +                self.last_index += 1
> +        elif key == 'meta enter':
> +            # When using multiline, enter inserts a new line into the
> editor
> +            # send the input to the server on alt + enter
> +            self.master.cb_send_to_server(msg)
> +            self.history.insert(0, msg)
> +            self.set_edit_text('')
> +            self.last_index = 0
> +            self.show_history = False
> +        else:
> +            self.show_history = False
> +            self.last_index = 0
> +            return cast(Optional[str], super().keypress(size, key))
> +        return None
> +
> +
> +class EditorWidget(urwid.Filler):
> +    """
> +    The Editor is a flow widget and has to wrapped inside a box widget.
> +    This class wraps the Editor inside filler widget.
> +    """
> +    def __init__(self, master: App) -> None:
> +        super().__init__(Editor(master), valign='top')
> +
> +
> +class HistoryBox(urwid.ListBox):
> +    """
> +    This widget is modelled using the ListBox widget, contains the list of
> +    all messages both QMP messages and log messsages to be shown in the
> TUI.
> +
> +    The messages are urwid.Text widgets. On every append of a message, the
> +    focus is shifted to the last appended message.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes the historybox widget
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        self.master = master
> +        self.history = urwid.SimpleFocusListWalker([])
> +        super().__init__(self.history)
> +
> +    def add_to_history(self, history: str) -> None:
> +        """
> +        Appends a message to the list and set the focus to the last
> appended
> +        message.
> +
> +        :param history:
> +            The history item(message/event) to be appended to the list.
> +        """
> +        self.history.append(urwid.Text(history))
> +        if self.history:
> +            self.history.set_focus(len(self.history) - 1)
> +
> +
> +class HistoryWindow(urwid.Frame):
> +    """
> +    This window composes the HistoryBox and EditorWidget in a horizontal
> split.
> +    By default the first focus is given to the history box.
> +    """
> +    def __init__(self, master: App) -> None:
> +        """
> +        Initializes this widget and its child widgets.
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        self.master = master
> +        self.editor_widget = EditorWidget(master)
> +        self.editor = urwid.LineBox(self.editor_widget)
> +        self.history = HistoryBox(master)
> +        self.body = urwid.Pile([('weight', 80, self.history),
> +                                ('weight', 20, self.editor)])
> +        super().__init__(self.body)
> +        urwid.connect_signal(self.master, UPDATE_MSG,
> self.cb_add_to_history)
> +
> +    def cb_add_to_history(self, msg: str, level: Optional[str] = None) ->
> None:
> +        """
> +        Appends a message to the history box
> +
> +        :param msg:
> +            The message to be appended to the history box.
> +        """
> +        if level:
> +            msg = f'[{level}]: {msg}'
> +        self.history.add_to_history(msg)
> +
> +
> +class Window(urwid.Frame):
> +    """
> +    This window is the top most widget of the TUI and will contain other
> +    windows. Each window is responsible for displaying a specific
>
+    functionality.
>

"each window" => "Each child of this widget", maybe?

+    For eg: The history window is responsible for showing the history of
> +    messages and the editor.
>

These lines can probably go.


> +    """
> +    def __init__(self, master: App) -> None:
>

Consider naming this "parent" instead, if you'd be so kind as to oblige me.
(And everywhere else in the file.)


> +        """
> +        Initializes this widget and its child windows.
> +
> +        :param master: Reference to the TUI object.
> +        """
> +        self.master = master
> +        footer = StatusBar()
> +        body = HistoryWindow(master)
> +        super().__init__(body, footer=footer)
> +
> +
> +class TUILogHandler(Handler):
> +    """
> +    This handler routes all the log messages to the TUI screen.
> +    It is installed to the root logger to so that the log message from all
> +    libraries begin used is routed to the screen.
> +    """
> +    def __init__(self, tui: App) -> None:
> +        """
> +        Initializes the handler class.
> +
> +        :param tui:
> +            Reference to the TUI object.
> +        """
> +        super().__init__()
> +        self.tui = tui
> +
> +    def emit(self, record: LogRecord) -> None:
> +        """
> +        Emits a record to the TUI screen.
> +
> +        Appends the log message to the TUI screen
> +        """
> +        level = record.levelname
> +        msg = record.getMessage()
> +        self.tui.add_to_history(msg, level)
> +
> +
> +def main() -> None:
> +    """
> +    Driver of the whole script, parses arguments, initialize the TUI and
> +    the logger.
> +    """
> +    parser = argparse.ArgumentParser(description='AQMP TUI')
> +    parser.add_argument('qmp_server', help='Address of the QMP server. '
> +                        'Format <UNIX socket path | TCP addr:port>')
> +    parser.add_argument('--log-file', help='The Log file name')
> +    parser.add_argument('--log-level', default='WARNING',
> +                        help='Log level
> <CRITICAL|ERROR|WARNING|INFO|DEBUG|>')
> +    parser.add_argument('--asyncio-debug', action='store_true',
> +                        help='Enable debug mode for asyncio loop. '
> +                        'Generates lot of output, makes TUI unusable when
> '
> +                        'logs are logged in the TUI. '
> +                        'Use only when logging to a file.')
> +    args = parser.parse_args()
> +
> +    try:
> +        address = QEMUMonitorProtocol.parse_address(args.qmp_server)
> +    except QMPBadPortError as err:
> +        parser.error(str(err))
> +
> +    app = App(address)
> +
> +    root_logger = logging.getLogger()
> +    root_logger.setLevel(logging.getLevelName(args.log_level))
> +
> +    if args.log_file:
> +        root_logger.addHandler(logging.FileHandler(args.log_file))
> +    else:
> +        root_logger.addHandler(TUILogHandler(app))
> +
> +    app.run(args.asyncio_debug)
> +
> +
> +if __name__ == '__main__':
> +    main()
> diff --git a/python/setup.cfg b/python/setup.cfg
> index a0ed3279d8..1ff2b907a2 100644
> --- a/python/setup.cfg
> +++ b/python/setup.cfg
> @@ -81,8 +81,19 @@ namespace_packages = True
>  # fusepy has no type stubs:
>  allow_subclassing_any = True
>
> +[mypy-qemu.aqmp.aqmp_tui]
> +# urwid and urwid_readline have no type stubs:
> +allow_subclassing_any = True
> +
> +# The following missing import directives are because these libraries do
> not
> +# provide type stubs. Allow them on an as-needed basis for mypy.
>  [mypy-fuse]
> -# fusepy has no type stubs:
> +ignore_missing_imports = True
> +
> +[mypy-urwid]
> +ignore_missing_imports = True
> +
> +[mypy-urwid_readline]
>  ignore_missing_imports = True
>
>  [pylint.messages control]
> @@ -97,7 +108,7 @@ ignore_missing_imports = True
>  # --disable=W".
>  disable=too-many-function-args,  # mypy handles this with less false
> positives.
>          no-member,  # mypy also handles this better.
> -        missing-docstring, # FIXME
> +        # missing-docstring, # FIXME
>          fixme, # FIXME
>
>  [pylint.basic]
> --
> 2.17.1
>
>
Most of the rest looks pretty good to me. I'm still quite a bit skeptical
of format_json, but I have to admit I will look a bit more closely at that
tomorrow -- and I want to take a closer look at has_tui_handler too, but
most of the rest seems like it's been stripped to its bare essentials,
which is good :)

Thanks for the work on the docstrings and mypy hints, it's in good shape
overall.

--js

[-- Attachment #2: Type: text/html, Size: 29732 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

* Re: [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft
  2021-08-22  7:33   ` John Snow
@ 2021-08-23 10:37     ` Niteesh G. S.
  0 siblings, 0 replies; 15+ messages in thread
From: Niteesh G. S. @ 2021-08-23 10:37 UTC (permalink / raw)
  To: John Snow
  Cc: Eduardo Habkost, Kashyap Chamarthy, Markus Armbruster,
	Wainer Moschetta, qemu-devel, Stefan Hajnoczi, Cleber Rosa,
	Eric Blake

[-- Attachment #1: Type: text/plain, Size: 23641 bytes --]

On Sun, Aug 22, 2021 at 1:04 PM John Snow <jsnow@redhat.com> wrote:

>
>
> On Thu, Aug 19, 2021 at 1:39 PM G S Niteesh Babu <niteesh.gs@gmail.com>
> wrote:
>
>> Added a draft of AQMP TUI.
>>
>> Implements the follwing basic features:
>> 1) Command transmission/reception.
>> 2) Shows events asynchronously.
>> 3) Shows server status in the bottom status bar.
>>
>> Also added type annotations and necessary pylint,
>> mypy configurations
>>
>> Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
>> ---
>>  python/qemu/aqmp/aqmp_tui.py | 566 +++++++++++++++++++++++++++++++++++
>>  python/setup.cfg             |  15 +-
>>  2 files changed, 579 insertions(+), 2 deletions(-)
>>  create mode 100644 python/qemu/aqmp/aqmp_tui.py
>>
>> diff --git a/python/qemu/aqmp/aqmp_tui.py b/python/qemu/aqmp/aqmp_tui.py
>> new file mode 100644
>> index 0000000000..12c9c4162a
>> --- /dev/null
>> +++ b/python/qemu/aqmp/aqmp_tui.py
>> @@ -0,0 +1,566 @@
>> +# Copyright (c) 2021
>> +#
>> +# Authors:
>> +#  Niteesh Babu G S <niteesh.gs@gmail.com>
>> +#
>> +# This work is licensed under the terms of the GNU GPL, version 2 or
>> +# later.  See the COPYING file in the top-level directory.
>> +"""
>> +AQMP TUI
>> +
>> +AQMP TUI is an asynchronous interface built on top the of the AQMP
>> library.
>> +It is the successor of QMP-shell and is bought-in as a replacement for
>> it.
>> +
>> +Example Usage: aqmp-tui <SOCKET | TCP IP:PORT>
>> +Full Usage: aqmp-tui --help
>> +"""
>> +
>> +import argparse
>> +import asyncio
>> +import logging
>> +from logging import Handler, LogRecord
>> +import signal
>> +from typing import (
>> +    List,
>> +    Optional,
>> +    Tuple,
>> +    Type,
>> +    Union,
>> +    cast,
>> +)
>> +
>> +import urwid
>> +import urwid_readline
>> +
>> +from ..qmp import QEMUMonitorProtocol, QMPBadPortError
>> +from .message import DeserializationError, Message, UnexpectedTypeError
>> +from .protocol import ConnectError
>> +from .qmp_client import ExecInterruptedError, QMPClient
>> +from .util import create_task, pretty_traceback
>> +
>> +
>> +# The name of the signal that is used to update the history list
>> +UPDATE_MSG: str = 'UPDATE_MSG'
>> +
>> +
>> +def format_json(msg: str) -> str:
>> +    """
>> +    Formats given multi-line JSON message into a single-line message.
>> +    Converting into single line is more asthetically pleasing when
>> looking
>> +    along with error messages.
>> +
>> +    Eg:
>> +    Input:
>> +          [ 1,
>> +            true,
>> +            3 ]
>> +    The above input is not a valid QMP message and produces the
>> following error
>> +    "QMP message is not a JSON object."
>> +    When displaying this in TUI in multiline mode we get
>> +
>> +        [ 1,
>> +          true,
>> +          3 ]: QMP message is not a JSON object.
>> +
>> +    whereas in singleline mode we get the following
>> +
>> +        [1, true, 3]: QMP message is not a JSON object.
>> +
>> +    The single line mode is more asthetically pleasing.
>> +
>> +    :param msg:
>> +        The message to formatted into single line.
>> +
>> +    :return: Formatted singleline message.
>> +
>> +    NOTE: We cannot use the JSON module here because it is only capable
>> of
>> +    format valid JSON messages. But here the goal is to also format
>> invalid
>> +    JSON messages.
>> +    """
>> +    msg = msg.replace('\n', '')
>> +    words = msg.split(' ')
>> +    words = [word for word in words if word != '']
>> +    return ' '.join(words)
>> +
>> +
>> +def has_tui_handler(logger: logging.Logger,
>> +                    handler_type: Type[Handler]) -> bool:
>> +    """
>> +    The Logger class has no interface to check if a certain type of
>> handler is
>> +    installed or not. So we provide an interface to do so.
>> +
>> +    :param logger:
>> +        Logger object
>> +    :param handler_type:
>> +        The type of the handler to be checked.
>> +
>> +    :return: returns True if handler of type `handler_type` is installed
>> else
>> +             False.
>> +    """
>> +    handlers = logger.handlers
>> +    for handler in handlers:
>> +        if isinstance(handler, handler_type):
>> +            return True
>> +    return False
>> +
>> +
>> +class App(QMPClient):
>> +    """
>> +    Implements the AQMP TUI.
>> +
>> +    Initializes the widgets and starts the urwid event loop.
>> +    """
>> +    def __init__(self, address: Union[str, Tuple[str, int]]) -> None:
>> +        """
>> +        Initializes the TUI.
>> +
>> +        :param address:
>> +            Address of the server to connect to.
>> +        """
>> +        urwid.register_signal(type(self), UPDATE_MSG)
>> +        self.window = Window(self)
>> +        self.address = address
>> +        self.aloop: Optional[asyncio.AbstractEventLoop] = None
>> +        super().__init__()
>> +
>> +    def add_to_history(self, msg: str, level: Optional[str] = None) ->
>> None:
>> +        """
>> +        Appends the msg to the history list.
>> +
>> +        :param msg:
>> +            The raw message to be appended in string type.
>> +        """
>> +        urwid.emit_signal(self, UPDATE_MSG, msg, level)
>> +
>> +    def _cb_outbound(self, msg: Message) -> Message:
>> +        """
>> +        Callback: outbound message hook.
>> +
>> +        Appends the outgoing messages to the history box.
>> +
>> +        :param msg: raw outbound message.
>> +        :return: final outbound message.
>> +        """
>> +        str_msg = str(msg)
>> +
>> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
>> +            logging.debug('Request: %s', str_msg)
>> +        self.add_to_history('<-- ' + str_msg)
>> +        return msg
>> +
>> +    def _cb_inbound(self, msg: Message) -> Message:
>> +        """
>> +        Callback: outbound message hook.
>> +
>> +        Appends the incoming messages to the history box.
>> +
>> +        :param msg: raw inbound message.
>> +        :return: final inbound message.
>> +        """
>> +        str_msg = str(msg)
>> +
>> +        if not has_tui_handler(logging.getLogger(), TUILogHandler):
>> +            logging.debug('Request: %s', str_msg)
>> +        self.add_to_history('--> ' + str_msg)
>> +        return msg
>> +
>> +    def handle_event(self, event: Message) -> None:
>> +        """
>> +        Handles the event.
>> +
>> +        :param event:
>> +            The event to be handled.
>> +        """
>> +        # TODO: Consider all states present in qapi/run-state.json
>> +        if event['event'] == 'SHUTDOWN':
>> +            self._set_status('[Server Shutdown]')
>> +
>> +    async def wait_for_events(self) -> None:
>> +        """
>> +        This coroutine continously waits for events and dispatches them.
>> +        """
>> +        async for event in self.events:
>> +            self.handle_event(event)
>> +
>> +    async def _send_to_server(self, msg: Message) -> None:
>> +        """
>> +        This coroutine sends the message to the server.
>> +        The message has to be pre-validated.
>> +
>> +        :param msg:
>> +            Pre-validated message to be to sent to the server.
>> +
>> +        :raise Exception: When an unhandled exception is caught.
>> +        """
>> +        try:
>> +            await self._raw(msg, assign_id='id' not in msg)
>> +        except ExecInterruptedError:
>> +            logging.info('Error server disconnected before reply')
>> +            self.add_to_history('Server disconnected before reply',
>> 'ERROR')
>> +            self._set_status("[Server Disconnected]")
>> +        except Exception as err:
>> +            logging.error('Exception from _send_to_server: %s', str(err))
>> +            raise err
>> +
>> +    def cb_send_to_server(self, raw_msg: str) -> None:
>> +        """
>> +        Validates and sends the message to the server.
>> +        The raw string message is first converted into a Message object
>> +        and is then sent to the server.
>> +
>> +        :param raw_msg:
>> +            The raw string message to be sent to the server.
>> +
>> +        :raise Exception: When an unhandled exception is caught.
>> +        """
>> +        try:
>> +            raw_msg = format_json(raw_msg)
>> +            msg = Message(bytes(raw_msg, encoding='utf-8'))
>> +            create_task(self._send_to_server(msg))
>> +        except (ValueError, TypeError) as err:
>> +            logging.info('Invalid message: %s', str(err))
>> +            self.add_to_history(f'{raw_msg}: {err}')
>> +        except (DeserializationError, UnexpectedTypeError) as err:
>> +            logging.info('Invalid message: %s', err.error_message)
>> +            self.add_to_history(f'{raw_msg}: {err.error_message}')
>> +
>> +    def unhandled_input(self, key: str) -> None:
>> +        """
>> +        Handle's keys which haven't been handled by the child widgets.
>> +
>> +        :param key:
>> +            Unhandled key
>> +        """
>> +        if key == 'esc':
>> +            self.kill_app()
>> +
>> +    def kill_app(self) -> None:
>> +        """
>> +        Initiates killing of app. A bridge between asynchronous and
>> synchronous
>> +        code.
>> +        """
>> +        create_task(self._kill_app())
>> +
>> +    async def _kill_app(self) -> None:
>> +        """
>> +        This coroutine initiates the actual disconnect process and calls
>> +        urwid.ExitMainLoop() to kill the TUI.
>> +
>> +        :raise Exception: When an unhandled exception is caught.
>> +        """
>> +        # It is ok to call disconnect even in disconnect state
>> +        try:
>> +            await self.disconnect()
>> +            logging.debug('Disconnect finished. Exiting app')
>> +        except EOFError:
>> +            # We receive an EOF during disconnect, ignore that
>> +            pass
>> +        except Exception as err:
>> +            logging.info('_kill_app: %s', str(err))
>> +            # Let the app crash after providing a proper stack trace
>> +            raise err
>> +        raise urwid.ExitMainLoop()
>> +
>> +    def _set_status(self, msg: str) -> None:
>> +        """
>> +        Sets the message as the status.
>> +
>> +        :param msg:
>> +            The message to be displayed in the status bar.
>> +        """
>> +        self.window.footer.set_text(msg)
>> +
>> +    def _get_formatted_address(self) -> str:
>> +        """
>> +        Returns a formatted version of the server's address.
>> +
>> +        :return: formatted address
>> +        """
>> +        if isinstance(self.address, tuple):
>> +            host, port = self.address
>> +            addr = f'{host}:{port}'
>> +        else:
>> +            addr = f'{self.address}'
>> +        return addr
>> +
>> +    async def connect_server(self) -> None:
>> +        """
>> +        Initiates a connection to the server at address `self.address`
>> +        and in case of a failure, sets the status to the respective
>> error.
>> +        """
>> +        try:
>> +            await self.connect(self.address)
>> +            addr = self._get_formatted_address()
>> +            self._set_status(f'Connected to {addr}')
>> +        except ConnectError as err:
>> +            logging.info('connect_server: ConnectError %s', str(err))
>> +            self._set_status(f'[ConnectError: {err.error_message}]')
>> +
>> +    def run(self, debug: bool = False) -> None:
>> +        """
>> +        Starts the long running co-routines and the urwid event loop.
>> +
>> +        :param debug:
>> +            Enables/Disables asyncio event loop debugging
>> +        """
>> +        self.aloop = asyncio.get_event_loop()
>> +        self.aloop.set_debug(debug)
>> +
>> +        # Gracefully handle SIGTERM and SIGINT signals
>> +        cancel_signals = [signal.SIGTERM, signal.SIGINT]
>> +        for sig in cancel_signals:
>> +            self.aloop.add_signal_handler(sig, self.kill_app)
>> +
>> +        event_loop = urwid.AsyncioEventLoop(loop=self.aloop)
>> +        main_loop = urwid.MainLoop(urwid.AttrMap(self.window,
>> 'background'),
>> +                                   unhandled_input=self.unhandled_input,
>> +                                   handle_mouse=True,
>> +                                   event_loop=event_loop)
>> +
>> +        create_task(self.wait_for_events(), self.aloop)
>> +        create_task(self.connect_server(), self.aloop)
>> +        try:
>> +            main_loop.run()
>> +        except Exception as err:
>> +            logging.error('%s\n%s\n', str(err), pretty_traceback())
>> +            raise err
>> +
>> +
>> +class StatusBar(urwid.Text):
>> +    """
>> +    A simple statusbar modelled using the Text widget. The status can be
>> +    set using the set_text function. All text set is aligned to right.
>> +    """
>> +    def __init__(self, text: str = ''):
>> +        super().__init__(text, align='right')
>> +
>> +
>> +class Editor(urwid_readline.ReadlineEdit):
>> +    """
>> +    A simple editor modelled using the urwid_readline.ReadlineEdit
>> widget.
>> +    Mimcs GNU readline shortcuts and provides history support.
>> +
>> +    The readline shortcuts can be found below:
>> +    https://github.com/rr-/urwid_readline#features
>> +
>> +    Along with the readline features, this editor also has support for
>> +    history. Pressing the 'up' arrow key with empty message box, lists
>> the
>> +    previous message inplace.
>> +
>> +    Currently there is no support to save the history to a file. The
>> history of
>> +    previous commands is lost on exit.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes the editor widget
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        super().__init__(caption='> ', multiline=True)
>> +        self.master = master
>> +        self.history: List[str] = []
>> +        self.last_index: int = -1
>> +        self.show_history: bool = False
>> +
>> +    def keypress(self, size: Tuple[int, int], key: str) -> Optional[str]:
>> +        """
>> +        Handles the keypress on this widget.
>> +
>> +        :param size:
>> +            The current size of the widget.
>> +        :param key:
>> +            The key to be handled.
>> +
>> +        :return: Unhandled key if any.
>> +        """
>> +        # TODO: Add some logic for down key and clean up logic if
>> possible.
>> +        # Returning None means the key has been handled by this widget
>> +        # which otherwise is propogated to the parent widget to be
>> +        # handled
>> +        msg = self.get_edit_text()
>> +        if key == 'up' and not msg:
>> +            # Show the history when 'up arrow' is pressed with no input
>> text.
>> +            # NOTE: The show_history logic is necessary because in
>> 'multiline'
>> +            # mode (which we use) 'up arrow' is used to move between
>> lines.
>> +            self.show_history = True
>> +            last_msg = self.history[self.last_index] if self.history
>> else ''
>> +            self.set_edit_text(last_msg)
>> +            self.edit_pos = len(last_msg)
>> +            self.last_index += 1
>> +        elif key == 'up' and self.show_history:
>> +            if self.last_index < len(self.history):
>> +                self.set_edit_text(self.history[self.last_index])
>> +                self.edit_pos = len(self.history[self.last_index])
>> +                self.last_index += 1
>> +        elif key == 'meta enter':
>> +            # When using multiline, enter inserts a new line into the
>> editor
>> +            # send the input to the server on alt + enter
>> +            self.master.cb_send_to_server(msg)
>> +            self.history.insert(0, msg)
>> +            self.set_edit_text('')
>> +            self.last_index = 0
>> +            self.show_history = False
>> +        else:
>> +            self.show_history = False
>> +            self.last_index = 0
>> +            return cast(Optional[str], super().keypress(size, key))
>> +        return None
>> +
>> +
>> +class EditorWidget(urwid.Filler):
>> +    """
>> +    The Editor is a flow widget and has to wrapped inside a box widget.
>> +    This class wraps the Editor inside filler widget.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        super().__init__(Editor(master), valign='top')
>> +
>> +
>> +class HistoryBox(urwid.ListBox):
>> +    """
>> +    This widget is modelled using the ListBox widget, contains the list
>> of
>> +    all messages both QMP messages and log messsages to be shown in the
>> TUI.
>> +
>> +    The messages are urwid.Text widgets. On every append of a message,
>> the
>> +    focus is shifted to the last appended message.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes the historybox widget
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        self.master = master
>> +        self.history = urwid.SimpleFocusListWalker([])
>> +        super().__init__(self.history)
>> +
>> +    def add_to_history(self, history: str) -> None:
>> +        """
>> +        Appends a message to the list and set the focus to the last
>> appended
>> +        message.
>> +
>> +        :param history:
>> +            The history item(message/event) to be appended to the list.
>> +        """
>> +        self.history.append(urwid.Text(history))
>> +        if self.history:
>> +            self.history.set_focus(len(self.history) - 1)
>> +
>> +
>> +class HistoryWindow(urwid.Frame):
>> +    """
>> +    This window composes the HistoryBox and EditorWidget in a horizontal
>> split.
>> +    By default the first focus is given to the history box.
>> +    """
>> +    def __init__(self, master: App) -> None:
>> +        """
>> +        Initializes this widget and its child widgets.
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        self.master = master
>> +        self.editor_widget = EditorWidget(master)
>> +        self.editor = urwid.LineBox(self.editor_widget)
>> +        self.history = HistoryBox(master)
>> +        self.body = urwid.Pile([('weight', 80, self.history),
>> +                                ('weight', 20, self.editor)])
>> +        super().__init__(self.body)
>> +        urwid.connect_signal(self.master, UPDATE_MSG,
>> self.cb_add_to_history)
>> +
>> +    def cb_add_to_history(self, msg: str, level: Optional[str] = None)
>> -> None:
>> +        """
>> +        Appends a message to the history box
>> +
>> +        :param msg:
>> +            The message to be appended to the history box.
>> +        """
>> +        if level:
>> +            msg = f'[{level}]: {msg}'
>> +        self.history.add_to_history(msg)
>> +
>> +
>> +class Window(urwid.Frame):
>> +    """
>> +    This window is the top most widget of the TUI and will contain other
>> +    windows. Each window is responsible for displaying a specific
>>
> +    functionality.
>>
>
> "each window" => "Each child of this widget", maybe?
>
Changed.

>
> +    For eg: The history window is responsible for showing the history of
>> +    messages and the editor.
>>
>
> These lines can probably go.
>
Removed them.

>
>
>> +    """
>> +    def __init__(self, master: App) -> None:
>>
>
> Consider naming this "parent" instead, if you'd be so kind as to oblige me.
> (And everywhere else in the file.)
>
Changed everywhere :)

>
>
>> +        """
>> +        Initializes this widget and its child windows.
>> +
>> +        :param master: Reference to the TUI object.
>> +        """
>> +        self.master = master
>> +        footer = StatusBar()
>> +        body = HistoryWindow(master)
>> +        super().__init__(body, footer=footer)
>> +
>> +
>> +class TUILogHandler(Handler):
>> +    """
>> +    This handler routes all the log messages to the TUI screen.
>> +    It is installed to the root logger to so that the log message from
>> all
>> +    libraries begin used is routed to the screen.
>> +    """
>> +    def __init__(self, tui: App) -> None:
>> +        """
>> +        Initializes the handler class.
>> +
>> +        :param tui:
>> +            Reference to the TUI object.
>> +        """
>> +        super().__init__()
>> +        self.tui = tui
>> +
>> +    def emit(self, record: LogRecord) -> None:
>> +        """
>> +        Emits a record to the TUI screen.
>> +
>> +        Appends the log message to the TUI screen
>> +        """
>> +        level = record.levelname
>> +        msg = record.getMessage()
>> +        self.tui.add_to_history(msg, level)
>> +
>> +
>> +def main() -> None:
>> +    """
>> +    Driver of the whole script, parses arguments, initialize the TUI and
>> +    the logger.
>> +    """
>> +    parser = argparse.ArgumentParser(description='AQMP TUI')
>> +    parser.add_argument('qmp_server', help='Address of the QMP server. '
>> +                        'Format <UNIX socket path | TCP addr:port>')
>> +    parser.add_argument('--log-file', help='The Log file name')
>> +    parser.add_argument('--log-level', default='WARNING',
>> +                        help='Log level
>> <CRITICAL|ERROR|WARNING|INFO|DEBUG|>')
>> +    parser.add_argument('--asyncio-debug', action='store_true',
>> +                        help='Enable debug mode for asyncio loop. '
>> +                        'Generates lot of output, makes TUI unusable
>> when '
>> +                        'logs are logged in the TUI. '
>> +                        'Use only when logging to a file.')
>> +    args = parser.parse_args()
>> +
>> +    try:
>> +        address = QEMUMonitorProtocol.parse_address(args.qmp_server)
>> +    except QMPBadPortError as err:
>> +        parser.error(str(err))
>> +
>> +    app = App(address)
>> +
>> +    root_logger = logging.getLogger()
>> +    root_logger.setLevel(logging.getLevelName(args.log_level))
>> +
>> +    if args.log_file:
>> +        root_logger.addHandler(logging.FileHandler(args.log_file))
>> +    else:
>> +        root_logger.addHandler(TUILogHandler(app))
>> +
>> +    app.run(args.asyncio_debug)
>> +
>> +
>> +if __name__ == '__main__':
>> +    main()
>> diff --git a/python/setup.cfg b/python/setup.cfg
>> index a0ed3279d8..1ff2b907a2 100644
>> --- a/python/setup.cfg
>> +++ b/python/setup.cfg
>> @@ -81,8 +81,19 @@ namespace_packages = True
>>  # fusepy has no type stubs:
>>  allow_subclassing_any = True
>>
>> +[mypy-qemu.aqmp.aqmp_tui]
>> +# urwid and urwid_readline have no type stubs:
>> +allow_subclassing_any = True
>> +
>> +# The following missing import directives are because these libraries do
>> not
>> +# provide type stubs. Allow them on an as-needed basis for mypy.
>>  [mypy-fuse]
>> -# fusepy has no type stubs:
>> +ignore_missing_imports = True
>> +
>> +[mypy-urwid]
>> +ignore_missing_imports = True
>> +
>> +[mypy-urwid_readline]
>>  ignore_missing_imports = True
>>
>>  [pylint.messages control]
>> @@ -97,7 +108,7 @@ ignore_missing_imports = True
>>  # --disable=W".
>>  disable=too-many-function-args,  # mypy handles this with less false
>> positives.
>>          no-member,  # mypy also handles this better.
>> -        missing-docstring, # FIXME
>> +        # missing-docstring, # FIXME
>>          fixme, # FIXME
>>
>>  [pylint.basic]
>> --
>> 2.17.1
>>
>>
> Most of the rest looks pretty good to me. I'm still quite a bit skeptical
> of format_json, but I have to admit I will look a bit more closely at that
> tomorrow -- and I want to take a closer look at has_tui_handler too, but
> most of the rest seems like it's been stripped to its bare essentials,
> which is good :)
>
Thanks :)

>
> Thanks for the work on the docstrings and mypy hints, it's in good shape
> overall.
>
Good to hear that :)

>
> --js
>

[-- Attachment #2: Type: text/html, Size: 31569 bytes --]

^ permalink raw reply	[flat|nested] 15+ messages in thread

end of thread, other threads:[~2021-08-23 10:39 UTC | newest]

Thread overview: 15+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2021-08-19 17:38 [PATCH v4 0/7] AQMP TUI Draft G S Niteesh Babu
2021-08-19 17:38 ` [PATCH v4 1/7] python: disable pylint errors for aqmp-tui G S Niteesh Babu
2021-08-19 17:38 ` [PATCH v4 2/7] python: Add dependencies for AQMP TUI G S Niteesh Babu
2021-08-21 19:54   ` John Snow
2021-08-19 17:38 ` [PATCH v4 3/7] python/aqmp-tui: Add AQMP TUI draft G S Niteesh Babu
2021-08-21 20:05   ` John Snow
2021-08-21 22:21     ` Niteesh G. S.
2021-08-22  7:33   ` John Snow
2021-08-23 10:37     ` Niteesh G. S.
2021-08-19 17:38 ` [PATCH v4 4/7] python: Add entry point for aqmp-tui G S Niteesh Babu
2021-08-19 17:38 ` [PATCH v4 5/7] python: add optional pygments dependency G S Niteesh Babu
2021-08-19 17:38 ` [PATCH v4 6/7] python/aqmp-tui: Add syntax highlighting G S Niteesh Babu
2021-08-19 17:38 ` [PATCH v4 7/7] python/aqmp-tui: Add QMP connection manager G S Niteesh Babu
2021-08-21  4:09 ` [PATCH v4 0/7] AQMP TUI Draft John Snow
2021-08-21 21:20   ` Niteesh G. S.

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).