From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on aws-us-west-2-korg-lkml-1.web.codeaurora.org X-Spam-Level: X-Spam-Status: No, score=-15.6 required=3.0 tests=BAYES_00,DKIM_INVALID, DKIM_SIGNED,HEADER_FROM_DIFFERENT_DOMAINS,HTML_MESSAGE,INCLUDES_CR_TRAILER, INCLUDES_PATCH,MAILING_LIST_MULTI,MENTIONS_GIT_HOSTING,SPF_HELO_NONE,SPF_PASS autolearn=ham autolearn_force=no version=3.4.0 Received: from mail.kernel.org (mail.kernel.org [198.145.29.99]) by smtp.lore.kernel.org (Postfix) with ESMTP id 446EBC4338F for ; Mon, 23 Aug 2021 19:02:45 +0000 (UTC) Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by mail.kernel.org (Postfix) with ESMTPS id A54A4613A7 for ; Mon, 23 Aug 2021 19:02:44 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.1 mail.kernel.org A54A4613A7 Authentication-Results: mail.kernel.org; dmarc=fail (p=none dis=none) header.from=redhat.com Authentication-Results: mail.kernel.org; spf=pass smtp.mailfrom=nongnu.org Received: from localhost ([::1]:34178 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1mIFDX-0003yf-TT for qemu-devel@archiver.kernel.org; Mon, 23 Aug 2021 15:02:43 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:48376) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIFBH-0001eJ-40 for qemu-devel@nongnu.org; Mon, 23 Aug 2021 15:00:23 -0400 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]:60297) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIFBB-0007bG-Uv for qemu-devel@nongnu.org; Mon, 23 Aug 2021 15:00:22 -0400 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1629745216; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: in-reply-to:in-reply-to:references:references; bh=/j9VoIu9OrPGxnRSBqJYC7ZttuBbeTCjCTYRepkrgBg=; b=R2SO7IXwgpTLRh3J6O8tPt5fJyhRzAFyoI3/Z4BXQy3DwGk5Jdfxak2q+LQBBQ67iV+GgS TKpkxoEiG3XEdNMjyi+k3nHExOra1PJIF33kubygPFxCs2ZmyjyD5jKruNEES7YEtWxOxm 69eENPo5umf7I9OcQhl0astIuBb+EvM= Received: from mail-ot1-f69.google.com (mail-ot1-f69.google.com [209.85.210.69]) (Using TLS) by relay.mimecast.com with ESMTP id us-mta-416-_DpqDCWoNCushGy8DFDC8Q-1; Mon, 23 Aug 2021 15:00:12 -0400 X-MC-Unique: _DpqDCWoNCushGy8DFDC8Q-1 Received: by mail-ot1-f69.google.com with SMTP id n4-20020a9d64c40000b02904f40ca6ab63so10651088otl.14 for ; Mon, 23 Aug 2021 12:00:12 -0700 (PDT) X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:mime-version:references:in-reply-to:from:date :message-id:subject:to:cc; bh=/j9VoIu9OrPGxnRSBqJYC7ZttuBbeTCjCTYRepkrgBg=; b=kmITSR27hB7V2K9EizwvPXa4iIj53H4WyV5Z3cMf65i/Yewa3t01M+JeAz3xPdv/LO o2Kj4HvYlKclCS3OmpF5LQlgjG4VmVPfbYr7dZ9EGzyR2TIAS/jKQvg+AzUsy/O/15SY 8pvwd9KwFMFk+erLnvlilu9WBzKER16k1QPF3Avbc2z8X3EIHj36Hv85oQXEMoKX/LPe tVbBY+DUgjJ4H7miROU1mTJ1oqYEs2ddPDSdt62LVkpl2hZ1vV/DEKCe0In4Ps3sDidw 5kvWRNcgwthnoTXvf5iUXUPI5flxjfb8wToEwOvDRLBwN61syret650P3fPSLvmpUvvx xeMQ== X-Gm-Message-State: AOAM532GI2mCytyCFOqmwYFTGiyftnHvZTF/r79YRntbIfe9K0eZFDZx MPkQ25CAKaNjXCloXL17oizYFXZyDKnSWYnOJHCsPA/eAb5ByWlAecMtP4lzdD8pguB8s16clAw g4+bmt1y0CoEIeXv21qrbcNYK675gFu4= X-Received: by 2002:a9d:12af:: with SMTP id g44mr15038656otg.45.1629745211783; Mon, 23 Aug 2021 12:00:11 -0700 (PDT) X-Google-Smtp-Source: ABdhPJx4NSdmKZzMdoKPbC5DOExTBUgdas/q8d4B2ojYNKAA1SP5KkqjXqUmrELqaIFvslNReoEO2fbMxKffw0L6YVY= X-Received: by 2002:a9d:12af:: with SMTP id g44mr15038629otg.45.1629745211491; Mon, 23 Aug 2021 12:00:11 -0700 (PDT) MIME-Version: 1.0 References: <20210823162938.32757-1-niteesh.gs@gmail.com> <20210823162938.32757-3-niteesh.gs@gmail.com> In-Reply-To: <20210823162938.32757-3-niteesh.gs@gmail.com> From: John Snow Date: Mon, 23 Aug 2021 15:00:01 -0400 Message-ID: Subject: Re: [PATCH v5 2/5] python/aqmp-tui: Add AQMP TUI To: G S Niteesh Babu Authentication-Results: relay.mimecast.com; auth=pass smtp.auth=CUSA124A263 smtp.mailfrom=jsnow@redhat.com X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Type: multipart/alternative; boundary="00000000000067d88205ca3ea085" Received-SPF: pass client-ip=170.10.133.124; envelope-from=jsnow@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -34 X-Spam_score: -3.5 X-Spam_bar: --- X-Spam_report: (-3.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.743, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, HTML_MESSAGE=0.001, RCVD_IN_DNSWL_LOW=-0.7, RCVD_IN_MSPIKE_H2=-0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Eduardo Habkost , Kashyap Chamarthy , Markus Armbruster , Wainer Moschetta , qemu-devel , Stefan Hajnoczi , Cleber Rosa , Eric Blake Errors-To: qemu-devel-bounces+qemu-devel=archiver.kernel.org@nongnu.org Sender: "Qemu-devel" --00000000000067d88205ca3ea085 Content-Type: text/plain; charset="UTF-8" On Mon, Aug 23, 2021 at 12:31 PM G S Niteesh Babu wrote: > Added AQMP TUI. > > Implements the follwing basic features: > 1) Command transmission/reception. > 2) Shows events asynchronously. > 3) Shows server status in the bottom status bar. > 4) Automatic retries on disconnects and error conditions. > > Also added type annotations and necessary pylint/mypy configurations. > > Signed-off-by: G S Niteesh Babu > --- > python/qemu/aqmp/aqmp_tui.py | 637 +++++++++++++++++++++++++++++++++++ > python/setup.cfg | 13 +- > 2 files changed, 649 insertions(+), 1 deletion(-) > 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..d3180e38bf > --- /dev/null > +++ b/python/qemu/aqmp/aqmp_tui.py > @@ -0,0 +1,637 @@ > +# Copyright (c) 2021 > +# > +# Authors: > +# Niteesh Babu G S > +# > +# 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 > +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 .error import ProtocolError > +from .message import DeserializationError, Message, UnexpectedTypeError > +from .protocol import ConnectError, Runstate > +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 != ''] > try list(filter(None, words)) -- it's a little easier to read. > + return ' '.join(words) > + > + > +def has_tui_handler(logger: logging.Logger, > + handler_type: Type[Handler]) -> bool: > maybe has_handler_type(...), since you wrote something a bit more generic than just checking for the TUI handler. > + """ > + 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. > If you wanted to fit this on one line, the "else False" is implied and could be omitted. > + """ > + handlers = logger.handlers > + for handler in handlers: > You could combine these lines if you wanted: for handler in logger.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]], 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 > + """ > Here and elsewhere, the init documentation can actually go into the class docstring. So you don't have to write stuff like "Initializes the TUI" everywhere. Take a look at how I do it in the rest of AQMP as a guide. > + 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.exiting: bool = False > + 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 > + > + 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 as err: > + logging.info('Error server disconnected before reply %s', > str(err)) > + self.add_to_history('Server disconnected before reply', > 'ERROR') > + await self.disconnect() > In this case, the connection manager will probably already have noticed that we were disconnected, so you can probably omit the call to disconnect here. > + 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) > Technically you're processing the message -- just a little bit. I'd prefer to pass the raw input straight to Message(...) if we could. > + 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}', 'ERROR') > + except (DeserializationError, UnexpectedTypeError) as err: > + logging.info('Invalid message: %s', err.error_message) > + self.add_to_history(f'{raw_msg}: {err.error_message}', > 'ERROR') > I see what you wanted to do here. You'd like to show a nice error message even when the message isn't a valid QMP message, or even valid JSON. In the case of UnexpectedTypeError, we know it was valid JSON but not valid QMP -- we can still use the JSON library to format this message. In the case of DeserializationError, it wasn't valid JSON at all -- and if you want nice formatting, you need to get creative. You could probably apply your format_json() function only in the DeserializationError case -- that way it's only being used for a fairly specific purpose, and if it isn't quite so rigorously good at formatting JSON, it doesn't matter. You could name it format_malformed_input to suggest what it's used for a bit more clearly, perhaps? > + > + 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. > + """ > + self.exiting = True > + 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. > + """ > + try: > + 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.error('disconnect: Unhandled exception %s', str(err)) > + self.retry = False > + raise err > What about for OSError problems, like ConnectionResetByPeer and so forth? You could probably rewrite this to be retry False by default, and then select the handful of cases where you know you want to retry. > + > + 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 _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 not self.exiting: > + 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) > + self.retry = False > + except ConnectError as err: > + logging.info('connect_server: ConnectError %s', str(err)) > + self.retry = True > + return err > + return None > + > + 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.manage_connection(), 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, parent: App) -> None: > + """ > + Initializes the editor widget > + > + :param parent: Reference to the TUI object. > + """ > + super().__init__(caption='> ', multiline=True) > + self.parent = parent > + self.history: List[str] = [] > + self.last_index: int = 0 > + 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. > + """ > + 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. > + if not self.history: > + return None > + self.show_history = True > + last_msg = self.history[self.last_index] > + self.set_edit_text(last_msg) > + self.edit_pos = len(last_msg) > + elif key == 'up' and self.show_history: > + self.last_index = min(self.last_index + 1, len(self.history) > - 1) > + self.set_edit_text(self.history[self.last_index]) > + self.edit_pos = len(self.history[self.last_index]) > + elif key == 'down' and self.show_history: > + if self.last_index == 0: > + self.set_edit_text('') > + self.show_history = False > + else: > + self.last_index -= 1 > + self.set_edit_text(self.history[self.last_index]) > + self.edit_pos = len(self.history[self.last_index]) > + 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.parent.cb_send_to_server(msg) > + self.history.insert(0, msg) > Why not append to the end? You can count backwards with list indices too, so you can look at history[-1], -2, -3, etc to go further backwards. > + 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, parent: App) -> None: > + super().__init__(Editor(parent), 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, parent: App) -> None: > + """ > + Initializes the historybox widget > + > + :param parent: Reference to the TUI object. > + """ > + self.parent = parent > + 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) > I assume this is something to work around a mypy error? if we've appended something to a list, then it should be impossible for the list to be empty, right? > > + > + def mouse_event(self, size: Tuple[int, int], _event: str, button: > float, > + _x: int, _y: int, focus: bool) -> None: > + # Unfortunately there are no urwid constants that represent the > below > + # events. > + if button == 4: # Scroll up event > + super().keypress(size, 'up') > + elif button == 5: # Scroll down event > + super().keypress(size, 'down') > + > + > +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, parent: App) -> None: > + """ > + Initializes this widget and its child widgets. > + > + :param parent: Reference to the TUI object. > + """ > + self.parent = parent > + self.editor_widget = EditorWidget(parent) > + self.editor = urwid.LineBox(self.editor_widget) > + self.history = HistoryBox(parent) > + self.body = urwid.Pile([('weight', 80, self.history), > + ('weight', 20, self.editor)]) > + super().__init__(self.body) > + urwid.connect_signal(self.parent, 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 child of this widget is responsible for displaying a > specific > + functionality. > + """ > + def __init__(self, parent: App) -> None: > + """ > + Initializes this widget and its child windows. > + > + :param parent: Reference to the TUI object. > + """ > + self.parent = parent > + footer = StatusBar() > + body = HistoryWindow(parent) > + 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 ') > + 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 > ') > + 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, args.num_retries, args.retry_delay) > + > + 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 589a90be21..e9ceaea637 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] > -- > 2.17.1 > > --00000000000067d88205ca3ea085 Content-Type: text/html; charset="UTF-8" Content-Transfer-Encoding: quoted-printable


=
On Mon, Aug 23, 2021 at 12:31 PM G S = Niteesh Babu <= niteesh.gs@gmail.com> wrote:
Added AQMP TUI.

Implements the follwing basic features:
1) Command transmission/reception.
2) Shows events asynchronously.
3) Shows server status in the bottom status bar.
4) Automatic retries on disconnects and error conditions.

Also added type annotations and necessary pylint/mypy configurations.

Signed-off-by: G S Niteesh Babu <niteesh.gs@gmail.com>
---
=C2=A0python/qemu/aqmp/aqmp_tui.py | 637 ++++++++++++++++++++++++++++++++++= +
=C2=A0python/setup.cfg=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0|=C2= =A0 13 +-
=C2=A02 files changed, 649 insertions(+), 1 deletion(-)
=C2=A0create 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..d3180e38bf
--- /dev/null
+++ b/python/qemu/aqmp/aqmp_tui.py
@@ -0,0 +1,637 @@
+# Copyright (c) 2021
+#
+# Authors:
+#=C2=A0 Niteesh Babu G S <niteesh.gs@gmail.com>
+#
+# This work is licensed under the terms of the GNU GPL, version 2 or
+# later.=C2=A0 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 (
+=C2=A0 =C2=A0 List,
+=C2=A0 =C2=A0 Optional,
+=C2=A0 =C2=A0 Tuple,
+=C2=A0 =C2=A0 Type,
+=C2=A0 =C2=A0 Union,
+=C2=A0 =C2=A0 cast,
+)
+
+import urwid
+import urwid_readline
+
+from ..qmp import QEMUMonitorProtocol, QMPBadPortError
+from .error import ProtocolError
+from .message import DeserializationError, Message, UnexpectedTypeError +from .protocol import ConnectError, Runstate
+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 =3D 'UPDATE_MSG'
+
+
+def format_json(msg: str) -> str:
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 Formats given multi-line JSON message into a single-line mes= sage.
+=C2=A0 =C2=A0 Converting into single line is more asthetically pleasing wh= en looking
+=C2=A0 =C2=A0 along with error messages.
+
+=C2=A0 =C2=A0 Eg:
+=C2=A0 =C2=A0 Input:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 [ 1,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 true,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 3 ]
+=C2=A0 =C2=A0 The above input is not a valid QMP message and produces the = following error
+=C2=A0 =C2=A0 "QMP message is not a JSON object."
+=C2=A0 =C2=A0 When displaying this in TUI in multiline mode we get
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 [ 1,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 true,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 3 ]: QMP message is not a JSON object.<= br> +
+=C2=A0 =C2=A0 whereas in singleline mode we get the following
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 [1, true, 3]: QMP message is not a JSON object= .
+
+=C2=A0 =C2=A0 The single line mode is more asthetically pleasing.
+
+=C2=A0 =C2=A0 :param msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 The message to formatted into single line.
+
+=C2=A0 =C2=A0 :return: Formatted singleline message.
+
+=C2=A0 =C2=A0 NOTE: We cannot use the JSON module here because it is only = capable of
+=C2=A0 =C2=A0 format valid JSON messages. But here the goal is to also for= mat invalid
+=C2=A0 =C2=A0 JSON messages.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 msg =3D msg.replace('\n', '')
+=C2=A0 =C2=A0 words =3D msg.split(' ')
+=C2=A0 =C2=A0 words =3D [word for word in words if word !=3D '']

try list(filter(None, words)) -- it'= s a little easier to read.
=C2=A0
+=C2=A0 =C2=A0 return ' '.join(words)
+
+
+def has_tui_handler(logger: logging.Logger,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 hand= ler_type: Type[Handler]) -> bool:

ma= ybe has_handler_type(...), since you wrote something a bit more generic tha= n just checking for the TUI handler.
=C2=A0
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 The Logger class has no interface to check if a certain type= of handler is
+=C2=A0 =C2=A0 installed or not. So we provide an interface to do so.
+
+=C2=A0 =C2=A0 :param logger:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Logger object
+=C2=A0 =C2=A0 :param handler_type:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 The type of the handler to be checked.
+
+=C2=A0 =C2=A0 :return: returns True if handler of type `handler_type` is i= nstalled else
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0False.

If you wanted to fit this on one line, the "else Fals= e" is implied and could be omitted.
=C2=A0
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 handlers =3D logger.handlers
+=C2=A0 =C2=A0 for handler in handlers:

You could combine these lines if you wanted: for handler in logger.handler= s: ...
=C2=A0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if isinstance(handler, handler_type):
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 return True
+=C2=A0 =C2=A0 return False
+
+
+class App(QMPClient):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 Implements the AQMP TUI.
+
+=C2=A0 =C2=A0 Initializes the widgets and starts the urwid event loop.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, address: Union[str, Tuple[str, int]], num= _retries: int,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0retry_delay:= Optional[int]) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initializes the TUI.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param address:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 Address of the server to connect= to.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param num_retries:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The number of times to retry bef= ore stopping to reconnect.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param retry_delay:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The delay(sec) before each retry=
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """

Here and elsewhere, the init documentation can actually go into th= e class docstring. So you don't have to write stuff like "Initiali= zes the TUI" everywhere. Take a look at how I do it in the rest of AQM= P as a guide.
=C2=A0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 urwid.register_signal(type(self), UPDATE_MSG)<= br> +=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.window =3D Window(self)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.address =3D address
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.aloop: Optional[asyncio.AbstractEventLoop= ] =3D None
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.num_retries =3D num_retries
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry_delay =3D retry_delay if retry_dela= y else 2
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry: bool =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.exiting: bool =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__()
+
+=C2=A0 =C2=A0 def add_to_history(self, msg: str, level: Optional[str] =3D = None) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Appends the msg to the history list.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The raw message to be appended i= n string type.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 urwid.emit_signal(self, UPDATE_MSG, msg, level= )
+
+=C2=A0 =C2=A0 def _cb_outbound(self, msg: Message) -> Message:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Callback: outbound message hook.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Appends the outgoing messages to the history b= ox.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param msg: raw outbound message.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :return: final outbound message.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 str_msg =3D str(msg)
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if not has_tui_handler(logging.getLogger(), TU= ILogHandler):
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.debug('Request: %s&#= 39;, str_msg)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.add_to_history('<-- ' + str_ms= g)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 return msg
+
+=C2=A0 =C2=A0 def _cb_inbound(self, msg: Message) -> Message:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Callback: outbound message hook.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Appends the incoming messages to the history b= ox.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param msg: raw inbound message.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :return: final inbound message.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 str_msg =3D str(msg)
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if not has_tui_handler(logging.getLogger(), TU= ILogHandler):
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.debug('Request: %s&#= 39;, str_msg)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.add_to_history('--> ' + str_ms= g)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 return msg
+
+=C2=A0 =C2=A0 async def _send_to_server(self, msg: Message) -> None: +=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 This coroutine sends the message to the server= .
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 The message has to be pre-validated.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 Pre-validated message to be to s= ent to the server.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :raise Exception: When an unhandled exception = is caught.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 try:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await self._raw(msg, assign_id= =3D'id' not in msg)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except ExecInterruptedError as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('Error server dis= connected before reply %s', str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.add_to_history('Server = disconnected before reply', 'ERROR')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await self.disconnect()

In this case, the connection manager will proba= bly already have noticed that we were disconnected, so you can probably omi= t the call to disconnect here.
=C2=A0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except Exception as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.error('Exception fro= m _send_to_server: %s', str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 raise err
+
+=C2=A0 =C2=A0 def cb_send_to_server(self, raw_msg: str) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Validates and sends the message to the server.=
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 The raw string message is first converted into= a Message object
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 and is then sent to the server.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param raw_msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The raw string message to be sen= t to the server.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :raise Exception: When an unhandled exception = is caught.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 try:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 raw_msg =3D format_json(raw_msg)=

Technically you're processing the = message -- just a little bit. I'd prefer to pass the raw input straight= to Message(...) if we could.
=C2=A0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 msg =3D Message(bytes(raw_msg, e= ncoding=3D'utf-8'))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 create_task(self._send_to_server= (msg))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except (ValueError, TypeError) as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('Invalid message:= %s', str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.add_to_history(f'{raw_m= sg}: {err}', 'ERROR')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except (DeserializationError, UnexpectedTypeEr= ror) as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('Invalid message:= %s', err.error_message)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.add_to_history(f'{raw_m= sg}: {err.error_message}', 'ERROR')

I see what you wanted to do here. You'd like to show a nice er= ror message even when the message isn't a valid QMP message, or even va= lid JSON.

In the case of UnexpectedTypeError, we k= now it was valid JSON but not valid QMP -- we can still use the JSON librar= y to format this message.
In the case of DeserializationError, it= wasn't valid JSON at all -- and if you want nice formatting, you need = to get creative.

You could probably apply your for= mat_json() function only in the DeserializationError case -- that way it= 9;s only being used for a fairly specific purpose, and if it isn't quit= e so rigorously good at formatting JSON, it doesn't matter. You could n= ame it format_malformed_input to suggest what it's used for a bit more = clearly, perhaps?
=C2=A0
+
+=C2=A0 =C2=A0 def unhandled_input(self, key: str) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Handle's keys which haven't been handl= ed by the child widgets.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param key:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 Unhandled key
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if key =3D=3D 'esc':
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.kill_app()
+
+=C2=A0 =C2=A0 def kill_app(self) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initiates killing of app. A bridge between asy= nchronous and synchronous
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 code.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 create_task(self._kill_app())
+
+=C2=A0 =C2=A0 async def _kill_app(self) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 This coroutine initiates the actual disconnect= process and calls
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 urwid.ExitMainLoop() to kill the TUI.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :raise Exception: When an unhandled exception = is caught.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.exiting =3D True
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 await self.disconnect()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.debug('Disconnect finished. Exitin= g app')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 raise urwid.ExitMainLoop()
+
+=C2=A0 =C2=A0 async def disconnect(self) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Overrides the disconnect method to handle the = errors locally.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 try:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await super().disconnect()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except EOFError as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('disconnect: %s&#= 39;, str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry =3D True
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except ProtocolError as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('disconnect: %s&#= 39;, str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except Exception as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.error('disconnect: U= nhandled exception %s', str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 raise err
<= br>
What about for OSError problems, like ConnectionResetByPeer a= nd so forth?
You could probably rewrite this to be retry False by= default, and then select the handful of cases where you know you want to r= etry.
=C2=A0
+
+=C2=A0 =C2=A0 def _set_status(self, msg: str) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Sets the message as the status.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The message to be displayed in t= he status bar.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.window.footer.set_text(msg)
+
+=C2=A0 =C2=A0 def _get_formatted_address(self) -> str:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Returns a formatted version of the server'= s address.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :return: formatted address
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if isinstance(self.address, tuple):
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 host, port =3D self.address
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 addr =3D f'{host}:{port}'= ;
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 else:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 addr =3D f'{self.address}= 9;
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 return addr
+
+=C2=A0 =C2=A0 async def _initiate_connection(self) -> Optional[ConnectE= rror]:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Tries connecting to a server a number of times= with a delay between
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 each try. If all retries failed then return th= e error faced during
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 the last retry.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :return: Error faced during last retry.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 current_retries =3D 0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 err =3D None
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 # initial try
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 await self.connect_server()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 while self.retry and current_retries < self= .num_retries:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('Connection Faile= d, retrying in %d', self.retry_delay)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 status =3D f'[Retry #{curren= t_retries} ({self.retry_delay}s)]'
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self._set_status(status)
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await asyncio.sleep(self.retry_d= elay)
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 err =3D await self.connect_serve= r()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 current_retries +=3D 1
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 # If all retries failed report the last error<= br> +=C2=A0 =C2=A0 =C2=A0 =C2=A0 if err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('All retries fail= ed: %s', err)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 return err
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 return None
+
+=C2=A0 =C2=A0 async def manage_connection(self) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Manage the connection based on the current run= state.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 A reconnect is issued when the current state i= s IDLE and the number
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 of retries is not exhausted.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 A disconnect is issued when the current state = is DISCONNECTING.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 while not self.exiting:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 if self.runstate =3D=3D Runstate= .IDLE:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 err =3D await self= ._initiate_connection()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # If retry is stil= l true then, we have exhausted all our tries.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 if err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self= ._set_status(f'[Error: {err.error_message}]')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 else:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 addr= =3D self._get_formatted_address()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self= ._set_status(f'[Connected {addr}]')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 elif self.runstate =3D=3D Runsta= te.DISCONNECTING:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self._set_status(&= #39;[Disconnected]')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await self.disconn= ect()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # check if a retry= is needed
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 if self.runstate = =3D=3D Runstate.IDLE:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 cont= inue
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await self.runstate_changed() +
+=C2=A0 =C2=A0 async def connect_server(self) -> Optional[ConnectError]:=
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initiates a connection to the server at addres= s `self.address`
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 and in case of a failure, sets the status to t= he respective error.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 try:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 await self.connect(self.address)=
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except ConnectError as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.info('connect_server: = ConnectError %s', str(err))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.retry =3D True
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 return err
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 return None
+
+=C2=A0 =C2=A0 def run(self, debug: bool =3D False) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Starts the long running co-routines and the ur= wid event loop.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param debug:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 Enables/Disables asyncio event l= oop debugging
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.aloop =3D asyncio.get_event_loop()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.aloop.set_debug(debug)
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 # Gracefully handle SIGTERM and SIGINT signals=
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 cancel_signals =3D [signal.SIGTERM, signal.SIG= INT]
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 for sig in cancel_signals:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.aloop.add_signal_handler(si= g, self.kill_app)
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 event_loop =3D urwid.AsyncioEventLoop(loop=3Ds= elf.aloop)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 main_loop =3D urwid.MainLoop(urwid.AttrMap(sel= f.window, 'background'),
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0unhandled_input=3Dself.= unhandled_input,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0handle_mouse=3DTrue, +=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0event_loop=3Devent_loop= )
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 create_task(self.manage_connection(), self.alo= op)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 try:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 main_loop.run()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 except Exception as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 logging.error('%s\n%s\n'= , str(err), pretty_traceback())
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 raise err
+
+
+class StatusBar(urwid.Text):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 A simple statusbar modelled using the Text widget. The statu= s can be
+=C2=A0 =C2=A0 set using the set_text function. All text set is aligned to = right.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, text: str =3D ''):
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__(text, align=3D'right'= )
+
+
+class Editor(urwid_readline.ReadlineEdit):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 A simple editor modelled using the urwid_readline.ReadlineEd= it widget.
+=C2=A0 =C2=A0 Mimcs GNU readline shortcuts and provides history support. +
+=C2=A0 =C2=A0 The readline shortcuts can be found below:
+=C2=A0 =C2=A0 https://github.com/rr-/urwid_readline#f= eatures
+
+=C2=A0 =C2=A0 Along with the readline features, this editor also has suppo= rt for
+=C2=A0 =C2=A0 history. Pressing the 'up' arrow key with empty mess= age box, lists the
+=C2=A0 =C2=A0 previous message inplace.
+
+=C2=A0 =C2=A0 Currently there is no support to save the history to a file.= The history of
+=C2=A0 =C2=A0 previous commands is lost on exit.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, parent: App) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initializes the editor widget
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param parent: Reference to the TUI object. +=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__(caption=3D'> ', mu= ltiline=3DTrue)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.parent =3D parent
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history: List[str] =3D []
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.last_index: int =3D 0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.show_history: bool =3D False
+
+=C2=A0 =C2=A0 def keypress(self, size: Tuple[int, int], key: str) -> Op= tional[str]:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Handles the keypress on this widget.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param size:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The current size of the widget.<= br> +=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param key:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The key to be handled.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :return: Unhandled key if any.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 msg =3D self.get_edit_text()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if key =3D=3D 'up' and not msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # Show the history when 'up = arrow' is pressed with no input text.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # NOTE: The show_history logic i= s necessary because in 'multiline'
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # mode (which we use) 'up ar= row' is used to move between lines.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 if not self.history:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 return None
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.show_history =3D True
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 last_msg =3D self.history[self.l= ast_index]
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.set_edit_text(last_msg)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.edit_pos =3D len(last_msg)<= br> +=C2=A0 =C2=A0 =C2=A0 =C2=A0 elif key =3D=3D 'up' and self.show_his= tory:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.last_index =3D min(self.las= t_index + 1, len(self.history) - 1)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.set_edit_text(self.history[= self.last_index])
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.edit_pos =3D len(self.histo= ry[self.last_index])
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 elif key =3D=3D 'down' and self.show_h= istory:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 if self.last_index =3D=3D 0:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.set_edit_text= ('')
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.show_history = =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 else:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.last_index -= =3D 1
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.set_edit_text= (self.history[self.last_index])
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.edit_pos =3D = len(self.history[self.last_index])
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 elif key =3D=3D 'meta enter':
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # When using multiline, enter in= serts a new line into the editor
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 # send the input to the server o= n alt + enter
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.parent.cb_send_to_server(ms= g)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history.insert(0, msg)
<= /blockquote>

Why not append to the end? You can count ba= ckwards with list indices too, so you can look at history[-1], -2, -3, etc = to go further backwards.
=C2=A0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.set_edit_text('') +=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.last_index =3D 0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.show_history =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 else:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.show_history =3D False
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.last_index =3D 0
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 return cast(Optional[str], super= ().keypress(size, key))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 return None
+
+
+class EditorWidget(urwid.Filler):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 The Editor is a flow widget and has to wrapped inside a box = widget.
+=C2=A0 =C2=A0 This class wraps the Editor inside filler widget.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, parent: App) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__(Editor(parent), valign=3D'= ;top')
+
+
+class HistoryBox(urwid.ListBox):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 This widget is modelled using the ListBox widget, contains t= he list of
+=C2=A0 =C2=A0 all messages both QMP messages and log messsages to be shown= in the TUI.
+
+=C2=A0 =C2=A0 The messages are urwid.Text widgets. On every append of a me= ssage, the
+=C2=A0 =C2=A0 focus is shifted to the last appended message.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, parent: App) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initializes the historybox widget
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param parent: Reference to the TUI object. +=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.parent =3D parent
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history =3D urwid.SimpleFocusListWalker([= ])
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__(self.history)
+
+=C2=A0 =C2=A0 def add_to_history(self, history: str) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Appends a message to the list and set the focu= s to the last appended
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 message.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param history:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The history item(message/event) = to be appended to the list.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history.append(urwid.Text(history))
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if self.history:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history.set_focus(len(self.= history) - 1)

I assume this is somethin= g to work around a mypy error? if we've appended something to a list, t= hen it should be impossible for the list to be empty, right?
=C2= =A0
+
+=C2=A0 =C2=A0 def mouse_event(self, size: Tuple[int, int], _event: str, bu= tton: float,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 _x: = int, _y: int, focus: bool) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 # Unfortunately there are no urwid constants t= hat represent the below
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 # events.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if button =3D=3D 4:=C2=A0 # Scroll up event +=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 super().keypress(size, 'up&#= 39;)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 elif button =3D=3D 5:=C2=A0 # Scroll down even= t
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 super().keypress(size, 'down= ')
+
+
+class HistoryWindow(urwid.Frame):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 This window composes the HistoryBox and EditorWidget in a ho= rizontal split.
+=C2=A0 =C2=A0 By default the first focus is given to the history box.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, parent: App) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initializes this widget and its child widgets.=
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param parent: Reference to the TUI object. +=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.parent =3D parent
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.editor_widget =3D EditorWidget(parent) +=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.editor =3D urwid.LineBox(self.editor_widg= et)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history =3D HistoryBox(parent)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.body =3D urwid.Pile([('weight', 8= 0, self.history),
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 ('weight', 20, self.editor)]= )
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__(self.body)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 urwid.connect_signal(self.parent, UPDATE_MSG, = self.cb_add_to_history)
+
+=C2=A0 =C2=A0 def cb_add_to_history(self, msg: str, level: Optional[str] = =3D None) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Appends a message to the history box
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param msg:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 The message to be appended to th= e history box.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 if level:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 msg =3D f'[{level}]: {msg}&#= 39;
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.history.add_to_history(msg)
+
+
+class Window(urwid.Frame):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 This window is the top most widget of the TUI and will conta= in other
+=C2=A0 =C2=A0 windows. Each child of this widget is responsible for displa= ying a specific
+=C2=A0 =C2=A0 functionality.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, parent: App) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initializes this widget and its child windows.=
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param parent: Reference to the TUI object. +=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.parent =3D parent
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 footer =3D StatusBar()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 body =3D HistoryWindow(parent)
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__(body, footer=3Dfooter)
+
+
+class TUILogHandler(Handler):
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 This handler routes all the log messages to the TUI screen.<= br> +=C2=A0 =C2=A0 It is installed to the root logger to so that the log messag= e from all
+=C2=A0 =C2=A0 libraries begin used is routed to the screen.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 def __init__(self, tui: App) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Initializes the handler class.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 :param tui:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 Reference to the TUI object.
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 super().__init__()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.tui =3D tui
+
+=C2=A0 =C2=A0 def emit(self, record: LogRecord) -> None:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Emits a record to the TUI screen.
+
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 Appends the log message to the TUI screen
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 level =3D record.levelname
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 msg =3D record.getMessage()
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 self.tui.add_to_history(msg, level)
+
+
+def main() -> None:
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 Driver of the whole script, parses arguments, initialize the= TUI and
+=C2=A0 =C2=A0 the logger.
+=C2=A0 =C2=A0 """
+=C2=A0 =C2=A0 parser =3D argparse.ArgumentParser(description=3D'AQMP T= UI')
+=C2=A0 =C2=A0 parser.add_argument('qmp_server', help=3D'Addres= s of the QMP server. '
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 'Format <UNIX socket path | TCP addr:port>')
+=C2=A0 =C2=A0 parser.add_argument('--num-retries', type=3Dint, def= ault=3D10,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 help=3D'Number of times to reconnect before giving up.')=
+=C2=A0 =C2=A0 parser.add_argument('--retry-delay', type=3Dint,
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 help=3D'Time(s) to wait before next retry. '
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 'Default action is to wait 2s between each retry.')
+=C2=A0 =C2=A0 parser.add_argument('--log-file', help=3D'The Lo= g file name')
+=C2=A0 =C2=A0 parser.add_argument('--log-level', default=3D'WA= RNING',
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 help=3D'Log level <CRITICAL|ERROR|WARNING|INFO|DEBUG|>= ')
+=C2=A0 =C2=A0 parser.add_argument('--asyncio-debug', action=3D'= ;store_true',
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 help=3D'Enable debug mode for asyncio loop. '
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 'Generates lot of output, makes TUI unusable when '
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 'logs are logged in the TUI. '
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2= =A0 =C2=A0 'Use only when logging to a file.')
+=C2=A0 =C2=A0 args =3D parser.parse_args()
+
+=C2=A0 =C2=A0 try:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 address =3D QEMUMonitorProtocol.parse_address(= args.qmp_server)
+=C2=A0 =C2=A0 except QMPBadPortError as err:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 parser.error(str(err))
+
+=C2=A0 =C2=A0 app =3D App(address, args.num_retries, args.retry_delay)
+
+=C2=A0 =C2=A0 root_logger =3D logging.getLogger()
+=C2=A0 =C2=A0 root_logger.setLevel(logging.getLevelName(args.log_level)) +
+=C2=A0 =C2=A0 if args.log_file:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 root_logger.addHandler(logging.FileHandler(arg= s.log_file))
+=C2=A0 =C2=A0 else:
+=C2=A0 =C2=A0 =C2=A0 =C2=A0 root_logger.addHandler(TUILogHandler(app))
+
+=C2=A0 =C2=A0 app.run(args.asyncio_debug)
+
+
+if __name__ =3D=3D '__main__':
+=C2=A0 =C2=A0 main()
diff --git a/python/setup.cfg b/python/setup.cfg
index 589a90be21..e9ceaea637 100644
--- a/python/setup.cfg
+++ b/python/setup.cfg
@@ -81,8 +81,19 @@ namespace_packages =3D True
=C2=A0# fusepy has no type stubs:
=C2=A0allow_subclassing_any =3D True

+[mypy-qemu.aqmp.aqmp_tui]
+# urwid and urwid_readline have no type stubs:
+allow_subclassing_any =3D True
+
+# The following missing import directives are because these libraries do n= ot
+# provide type stubs. Allow them on an as-needed basis for mypy.
=C2=A0[mypy-fuse]
-# fusepy has no type stubs:
+ignore_missing_imports =3D True
+
+[mypy-urwid]
+ignore_missing_imports =3D True
+
+[mypy-urwid_readline]
=C2=A0ignore_missing_imports =3D True

=C2=A0[pylint.messages control]
--
2.17.1

--00000000000067d88205ca3ea085--