From nobody Sun May 5 20:29:32 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=gmail.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1629758264446192.59220418828613; Mon, 23 Aug 2021 15:37:44 -0700 (PDT) Received: from localhost ([::1]:36540 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1mIIZb-0000vy-Dh for importer@patchew.org; Mon, 23 Aug 2021 18:37:43 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:42840) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIIY5-00083a-FP for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:36:09 -0400 Received: from mail-ot1-x329.google.com ([2607:f8b0:4864:20::329]:44800) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1mIIY4-0005kP-2l for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:36:09 -0400 Received: by mail-ot1-x329.google.com with SMTP id g66-20020a9d12c8000000b0051aeba607f1so32158470otg.11 for ; Mon, 23 Aug 2021 15:36:07 -0700 (PDT) Received: from localhost.localdomain ([120.138.13.180]) by smtp.gmail.com with ESMTPSA id j21sm16217454pfj.66.2021.08.23.15.07.57 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 23 Aug 2021 15:08:01 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references; bh=h5KtKMWDDVs8IAOwL+94ObAhGladPMl23HCiYjqXkEo=; b=P2rrMIdWeCdJxaFglBKLUf7xMOTdXrQ9qqK3hCQAHDpgE32G+YiKSv5lWXMwP6fa4x OCvwgzUdyveRnoetSRnzmhzCO74qrinN3wV2ASt9zFcqtD1lMHxWL1cHqaBAI5uas5/b fDLhh+4hyRc4gK44RWkXUk00pOM3okJ4/sD2STJYu8PZRkzviWbiTDRjXOrIQK4kTWgk KG7+ks1dCG/5fuD1ZQohzH44Ge60m1fNmiVtZD+vxeTh7uCg+8bpAY3MD5I0gzxtekG7 N1YJEjWC+d7gIVjFEb8suqdx1YwI53zd1L9+OwRE7eeBifoPsOpzQRoqtF/2LhDh5Rrj OoeA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references; bh=h5KtKMWDDVs8IAOwL+94ObAhGladPMl23HCiYjqXkEo=; b=cTkdgdT764Xg7HcdhZ1q/SNwcd5gwjKefl5bSN5LHlOAAj6CGBOA8naSl+Byg4mmY2 3z1cXC2+HQVyvxXBL40/7m7qr498t8XEqYmuJrCzZpszSLYZZKQCU9W21q/x4EEwBeHu t94ridg7lIJyHWKPf1TjkZr46PYMy/krYO5TCL+pfndmoI8FEL59Ma/LAQ17i27/B8/L YG1ILSgjbk5AyqBDk+Xfb0sa/W7vxt4IWenhn8rAL17Phsy/K5L+6mthPzVps9my9QDC 118aofdbS+xKGgXgpRUESfHYtCJ16ORM7YELM4xEs7YyD1NPo2NwPUtiuBarjrTSCa7M G3Eg== X-Gm-Message-State: AOAM531D/3zOeKIVSJDAoZha1GdEShcwvYHYsf0b+RMh8o8RTVN0nW2/ 8AQzRo33gPnGgkM/ufdVeexzLMNcE/4= X-Google-Smtp-Source: ABdhPJzRfDSxUULmrxlUSUNHXtkM4hRc2keXhEigDjdBbfu9hl1hBhsZdWfjAqV6gAkncaWqh8AxQQ== X-Received: by 2002:a17:90a:e416:: with SMTP id hv22mr740552pjb.232.1629756481456; Mon, 23 Aug 2021 15:08:01 -0700 (PDT) From: G S Niteesh Babu To: qemu-devel@nongnu.org Subject: [PATCH v6 1/5] python: Add dependencies for AQMP TUI Date: Tue, 24 Aug 2021 03:37:42 +0530 Message-Id: <20210823220746.28295-2-niteesh.gs@gmail.com> X-Mailer: git-send-email 2.17.1 In-Reply-To: <20210823220746.28295-1-niteesh.gs@gmail.com> References: <20210823220746.28295-1-niteesh.gs@gmail.com> Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2607:f8b0:4864:20::329; envelope-from=niteesh.gs@gmail.com; helo=mail-ot1-x329.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, FREEMAIL_FROM=0.001, RCVD_IN_DNSWL_NONE=-0.0001, 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: ehabkost@redhat.com, kchamart@redhat.com, jsnow@redhat.com, armbru@redhat.com, wainersm@redhat.com, G S Niteesh Babu , stefanha@redhat.com, crosa@redhat.com, eblake@redhat.com Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1629758265140100001 Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" 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 --- 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": "=3D=3D3.10.0.0" }, + "urwid": { + "hashes": [ + "sha256:588bee9c1cb208d0906a9f73c613d2bd32c3ed3702012f51ef= e318a3f2127eae" + ], + "version": "=3D=3D2.1.2" + }, + "urwid-readline": { + "hashes": [ + "sha256:018020cbc864bb5ed87be17dc26b069eae2755cb29f3a9c569= aac3bded1efaf4" + ], + "version": "=3D=3D0.13" + }, "virtualenv": { "hashes": [ "sha256:14fdf849f80dbb29a4eb6caa9875d476ee2a5cf76a5f5415fa= 2f1606010ab467", diff --git a/python/setup.cfg b/python/setup.cfg index 152c683f41..589a90be21 100644 --- a/python/setup.cfg +++ b/python/setup.cfg @@ -44,11 +44,18 @@ devel =3D mypy >=3D 0.770 pylint >=3D 2.8.0 tox >=3D 3.18.0 + urwid >=3D 2.1.2 + urwid-readline >=3D 0.13 =20 # Provides qom-fuse functionality fuse =3D fusepy >=3D 2.0.4 =20 +# AQMP TUI dependencies +tui =3D + urwid >=3D 2.1.2 + urwid-readline >=3D 0.13 + [options.entry_points] console_scripts =3D qom =3D qemu.qmp.qom:main @@ -132,5 +139,6 @@ allowlist_externals =3D make deps =3D .[devel] .[fuse] # Workaround to trigger tox venv rebuild + .[tui] # Workaround to trigger tox venv rebuild commands =3D make check --=20 2.17.1 From nobody Sun May 5 20:29:32 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=gmail.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1629758494295677.8274355188336; Mon, 23 Aug 2021 15:41:34 -0700 (PDT) Received: from localhost ([::1]:45694 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1mIIdJ-0007Mh-1T for importer@patchew.org; Mon, 23 Aug 2021 18:41:33 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:43346) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIIas-0003r7-BH for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:39:03 -0400 Received: from mail-pg1-x52f.google.com ([2607:f8b0:4864:20::52f]:40716) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1mIIak-0007TW-MV for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:39:01 -0400 Received: by mail-pg1-x52f.google.com with SMTP id y23so17972573pgi.7 for ; Mon, 23 Aug 2021 15:38:54 -0700 (PDT) Received: from localhost.localdomain ([120.138.13.180]) by smtp.gmail.com with ESMTPSA id j21sm16217454pfj.66.2021.08.23.15.08.01 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 23 Aug 2021 15:08:04 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references; bh=QkDclNF121D+fpX6JJJ14Ju4BW//UQVmHnSpxOPklYI=; b=S82hjSh3VKCRUbpvZctEPC4zOWzSSKlTrPEK89qmSRm5FCXyqrX7+Y+KmgqOKnJgv6 Ep6RxwDMpQnV8xaKX2h8EIXKIw95ncUZOL+FmTFY82XUoT7Od7JYQaY0/pL1P4msGyrK ApINds/KPRtElLGR2U82eRJaZDrYJjO3MtnNVmqY1qUiRL065MzktnrfBtYrz+iaR+uu skznAgSpU7C2cuMT7NXmkE+HHZEO8srQxsW2Hfnrq3MVB46cqL9k6H97g+IuTgpPH9ea 88mCxgePlm4PzqUeenWR70g9TWil53YJif94/6mSx9FziGBUlDs1dzwJ7SmsFSfLOfdL +iBQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references; bh=QkDclNF121D+fpX6JJJ14Ju4BW//UQVmHnSpxOPklYI=; b=J9NKrY+Gm/diRy8vx9ZIx0It7Fqzo4pvGdGrTmMm305S6U7/zrfn/DBpdbzC9orpEb XpR6Ovf/ZYjKncJ80qz+XE3J6vjKH/EFI0agioTI8okpLi2Euqe6GFq7mSmWDcYq3cQD MK79SCRNTiITsHlYnWCEElgWhQji4qeL36K6pUeKh9iLTI2KCmI/GLDQtUEaN0zkRRYq U2CY3GnWM/xhF/rgAtgMCwKpjo11LMDVavwlZBwaXKmdycR6e9IuV94jWI07J6C9BhiC Bx6NwvWNz9N7JJTlutg+EDk1pZZ7hAVAYqOm5OVCsNE64m2gjGJCC06ojOOlk//o7/6B YjkA== X-Gm-Message-State: AOAM533YC+bkp/6ybh5QDJEi1lkA5Y9LZXyaB7ZKLbOTONj+iLx3nD2Z HR4BvuyZd1xcavsiejmGvyEiuF1LxYU= X-Google-Smtp-Source: ABdhPJy1UYCN/UDcU1AFWE8w5i7W54VL1wAhBCdBjCxPjtMOUFwtELz6weRDB3RFaQVTeY6cPDjOyQ== X-Received: by 2002:a63:58d:: with SMTP id 135mr34137893pgf.441.1629756484913; Mon, 23 Aug 2021 15:08:04 -0700 (PDT) From: G S Niteesh Babu To: qemu-devel@nongnu.org Subject: [PATCH v6 2/5] python/aqmp-tui: Add AQMP TUI Date: Tue, 24 Aug 2021 03:37:43 +0530 Message-Id: <20210823220746.28295-3-niteesh.gs@gmail.com> X-Mailer: git-send-email 2.17.1 In-Reply-To: <20210823220746.28295-1-niteesh.gs@gmail.com> References: <20210823220746.28295-1-niteesh.gs@gmail.com> Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2607:f8b0:4864:20::52f; envelope-from=niteesh.gs@gmail.com; helo=mail-pg1-x52f.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, FREEMAIL_FROM=0.001, RCVD_IN_DNSWL_NONE=-0.0001, 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: ehabkost@redhat.com, kchamart@redhat.com, jsnow@redhat.com, armbru@redhat.com, wainersm@redhat.com, G S Niteesh Babu , stefanha@redhat.com, crosa@redhat.com, eblake@redhat.com Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1629758494878100001 Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" 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 | 620 +++++++++++++++++++++++++++++++++++ python/setup.cfg | 13 +- 2 files changed, 632 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..ac533541d2 --- /dev/null +++ b/python/qemu/aqmp/aqmp_tui.py @@ -0,0 +1,620 @@ +# 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 json +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 =3D 'UPDATE_MSG' + + +def format_json(msg: str) -> str: + """ + Formats valid/invalid multi-line JSON message into a single-line messa= ge. + + Formatting is first tried using the standard json module. If that fails + due to an decoding error then a simple string manipulation is done to + achieve a single line JSON string. + + 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. + """ + try: + msg =3D json.loads(msg) + return str(json.dumps(msg)) + except json.decoder.JSONDecodeError: + msg =3D msg.replace('\n', '') + words =3D msg.split(' ') + words =3D list(filter(None, words)) + return ' '.join(words) + + +def has_handler_type(logger: logging.Logger, + handler_type: Type[Handler]) -> bool: + """ + The Logger class has no interface to check if a certain type of handle= r 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`. + """ + 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. + + :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 + """ + def __init__(self, address: Union[str, Tuple[str, int]], num_retries: = int, + retry_delay: Optional[int]) -> None: + urwid.register_signal(type(self), UPDATE_MSG) + self.window =3D Window(self) + self.address =3D address + self.aloop: Optional[asyncio.AbstractEventLoop] =3D None + self.num_retries =3D num_retries + self.retry_delay =3D retry_delay if retry_delay else 2 + self.retry: bool =3D False + self.exiting: bool =3D False + super().__init__() + + def add_to_history(self, msg: str, level: Optional[str] =3D None) -> N= one: + """ + 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 =3D str(msg) + + if not has_handler_type(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 =3D str(msg) + + if not has_handler_type(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=3D'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= ') + 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: + msg =3D Message(bytes(raw_msg, encoding=3D'utf-8')) + create_task(self._send_to_server(msg)) + except (DeserializationError, UnexpectedTypeError) as err: + raw_msg =3D format_json(raw_msg) + logging.info('Invalid message: %s', err.error_message) + self.add_to_history(f'{raw_msg}: {err.error_message}', 'ERROR') + + 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 =3D=3D 'esc': + self.kill_app() + + def kill_app(self) -> None: + """ + Initiates killing of app. A bridge between asynchronous and synchr= onous + 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 =3D 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() + except (OSError, EOFError) as err: + logging.info('disconnect: %s', str(err)) + self.retry =3D True + except ProtocolError as err: + logging.info('disconnect: %s', str(err)) + except Exception as err: + logging.error('disconnect: Unhandled exception %s', str(err)) + raise err + + 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 =3D self.address + addr =3D f'{host}:{port}' + else: + addr =3D 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 =3D 0 + err =3D 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_d= elay) + status =3D f'[Retry #{current_retries} ({self.retry_delay}s)]' + self._set_status(status) + + await asyncio.sleep(self.retry_delay) + + err =3D await self.connect_server() + current_retries +=3D 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 =3D=3D Runstate.IDLE: + err =3D await self._initiate_connection() + # If retry is still true then, we have exhausted all our t= ries. + if err: + self._set_status(f'[Error: {err.error_message}]') + else: + addr =3D self._get_formatted_address() + self._set_status(f'[Connected {addr}]') + elif self.runstate =3D=3D Runstate.DISCONNECTING: + self._set_status('[Disconnected]') + await self.disconnect() + # check if a retry is needed + if self.runstate =3D=3D 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 =3D False + except ConnectError as err: + logging.info('connect_server: ConnectError %s', str(err)) + self.retry =3D True + return err + return None + + def run(self, debug: bool =3D False) -> None: + """ + Starts the long running co-routines and the urwid event loop. + + :param debug: + Enables/Disables asyncio event loop debugging + """ + self.aloop =3D asyncio.get_event_loop() + self.aloop.set_debug(debug) + + # Gracefully handle SIGTERM and SIGINT signals + cancel_signals =3D [signal.SIGTERM, signal.SIGINT] + for sig in cancel_signals: + self.aloop.add_signal_handler(sig, self.kill_app) + + event_loop =3D urwid.AsyncioEventLoop(loop=3Dself.aloop) + main_loop =3D urwid.MainLoop(urwid.AttrMap(self.window, 'backgroun= d'), + unhandled_input=3Dself.unhandled_input, + handle_mouse=3DTrue, + event_loop=3Devent_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. + + :param text: Initial text to be displayed. Default is empty str. + """ + def __init__(self, text: str =3D ''): + super().__init__(text, align=3D'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'/'down' switches between the prev/next messa= ges + available in the history. + + Currently there is no support to save the history to a file. The histo= ry of + previous commands is lost on exit. + + :param parent: Reference to the TUI object. + """ + def __init__(self, parent: App) -> None: + super().__init__(caption=3D'> ', multiline=3DTrue) + self.parent =3D parent + self.history: List[str] =3D [] + self.last_index: int =3D -1 + self.show_history: bool =3D 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 =3D self.get_edit_text() + if key =3D=3D 'up' and not msg: + # Show the history when 'up arrow' is pressed with no input te= xt. + # NOTE: The show_history logic is necessary because in 'multil= ine' + # mode (which we use) 'up arrow' is used to move between lines. + if not self.history: + return None + self.show_history =3D True + last_msg =3D self.history[self.last_index] + self.set_edit_text(last_msg) + self.edit_pos =3D len(last_msg) + elif key =3D=3D 'up' and self.show_history: + self.last_index =3D max(self.last_index - 1, -len(self.history= )) + self.set_edit_text(self.history[self.last_index]) + self.edit_pos =3D len(self.history[self.last_index]) + elif key =3D=3D 'down' and self.show_history: + if self.last_index =3D=3D -1: + self.set_edit_text('') + self.show_history =3D False + else: + self.last_index +=3D 1 + self.set_edit_text(self.history[self.last_index]) + self.edit_pos =3D len(self.history[self.last_index]) + elif key =3D=3D 'meta enter': + # When using multiline, enter inserts a new line into the edit= or + # send the input to the server on alt + enter + self.parent.cb_send_to_server(msg) + self.history.append(msg) + self.set_edit_text('') + self.last_index =3D -1 + self.show_history =3D False + else: + self.show_history =3D False + self.last_index =3D -1 + return cast(Optional[str], super().keypress(size, key)) + return None + + +class EditorWidget(urwid.Filler): + """ + Wrapper around the editor widget. + + The Editor is a flow widget and has to wrapped inside a box widget. + This class wraps the Editor inside filler widget. + + :param parent: Reference to the TUI object. + """ + def __init__(self, parent: App) -> None: + super().__init__(Editor(parent), valign=3D'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 TU= I. + + The messages are urwid.Text widgets. On every append of a message, the + focus is shifted to the last appended message. + + :param parent: Reference to the TUI object. + """ + def __init__(self, parent: App) -> None: + self.parent =3D parent + self.history =3D 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 append= ed + message. + + :param history: + The history item(message/event) to be appended to the list. + """ + self.history.append(urwid.Text(history)) + self.history.set_focus(len(self.history) - 1) + + def mouse_event(self, size: Tuple[int, int], _event: str, button: floa= t, + _x: int, _y: int, focus: bool) -> None: + # Unfortunately there are no urwid constants that represent the mo= use + # events. + if button =3D=3D 4: # Scroll up event + super().keypress(size, 'up') + elif button =3D=3D 5: # Scroll down event + super().keypress(size, 'down') + + +class HistoryWindow(urwid.Frame): + """ + This window composes the HistoryBox and EditorWidget in a horizontal s= plit. + By default the first focus is given to the history box. + + :param parent: Reference to the TUI object. + """ + def __init__(self, parent: App) -> None: + self.parent =3D parent + self.editor_widget =3D EditorWidget(parent) + self.editor =3D urwid.LineBox(self.editor_widget) + self.history =3D HistoryBox(parent) + self.body =3D 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_histo= ry) + + def cb_add_to_history(self, msg: str, level: Optional[str] =3D None) -= > None: + """ + Appends a message to the history box + + :param msg: + The message to be appended to the history box. + """ + if level: + msg =3D 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 spe= cific + functionality. + + :param parent: Reference to the TUI object. + """ + def __init__(self, parent: App) -> None: + self.parent =3D parent + footer =3D StatusBar() + body =3D HistoryWindow(parent) + super().__init__(body, footer=3Dfooter) + + +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. + + :param tui: Reference to the TUI object. + """ + def __init__(self, tui: App) -> None: + super().__init__() + self.tui =3D tui + + def emit(self, record: LogRecord) -> None: + """ + Emits a record to the TUI screen. + + Appends the log message to the TUI screen + """ + level =3D record.levelname + msg =3D 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 =3D argparse.ArgumentParser(description=3D'AQMP TUI') + parser.add_argument('qmp_server', help=3D'Address of the QMP server. ' + 'Format ') + parser.add_argument('--num-retries', type=3Dint, default=3D10, + help=3D'Number of times to reconnect before giving= up.') + parser.add_argument('--retry-delay', type=3Dint, + help=3D'Time(s) to wait before next retry. ' + 'Default action is to wait 2s between each retry.') + parser.add_argument('--log-file', help=3D'The Log file name') + parser.add_argument('--log-level', default=3D'WARNING', + help=3D'Log level ') + parser.add_argument('--asyncio-debug', action=3D'store_true', + help=3D'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 =3D parser.parse_args() + + try: + address =3D QEMUMonitorProtocol.parse_address(args.qmp_server) + except QMPBadPortError as err: + parser.error(str(err)) + + app =3D App(address, args.num_retries, args.retry_delay) + + root_logger =3D 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__ =3D=3D '__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 =3D True # fusepy has no type stubs: allow_subclassing_any =3D True =20 +[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. [mypy-fuse] -# fusepy has no type stubs: +ignore_missing_imports =3D True + +[mypy-urwid] +ignore_missing_imports =3D True + +[mypy-urwid_readline] ignore_missing_imports =3D True =20 [pylint.messages control] --=20 2.17.1 From nobody Sun May 5 20:29:32 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=gmail.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1629758400605537.2424769588085; Mon, 23 Aug 2021 15:40:00 -0700 (PDT) Received: from localhost ([::1]:42182 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1mIIbn-0004mf-Kp for importer@patchew.org; Mon, 23 Aug 2021 18:39:59 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:43286) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIIaV-0003M4-F3 for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:38:39 -0400 Received: from mail-pf1-x436.google.com ([2607:f8b0:4864:20::436]:43764) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1mIIaT-0007IU-RI for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:38:39 -0400 Received: by mail-pf1-x436.google.com with SMTP id 7so16641426pfl.10 for ; Mon, 23 Aug 2021 15:38:37 -0700 (PDT) Received: from localhost.localdomain ([120.138.13.180]) by smtp.gmail.com with ESMTPSA id j21sm16217454pfj.66.2021.08.23.15.08.05 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 23 Aug 2021 15:08:08 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references; bh=9YhbKwcUIZlKjGGWVi9LMyqnGm4JxOOty0zVYcxDAZE=; b=qoXxe7aS8KGwN5axf9JYFakx+SsSeOKou40/nw4F+8mwi1YIkLVCfASGzIfgnbSzXN ShXoPlrdghgKGbALTPesTH6xTmCa0lAk1x4iR64J6bOCUa5s7MjOVAOqh7VnGlnyj21y X9GbfeuWZL+CI+Ku4dPhFhxsYOaIycRMZlEhfa4xk65fpTRtOirG7urGOrmkYxXa7n8I fIOYG0g77PfRQfoROroXXLlNU30rbvbzP38/hspHLnRJxOy1im6QUtNpzV57PiPKsmX8 G9gATGw3qKOSXZB81PZtQm5vd8iDLw1SFUCyQ0AXSvJ/+yIvYiUuuALkYpbMbHjKTJQ9 TgyQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references; bh=9YhbKwcUIZlKjGGWVi9LMyqnGm4JxOOty0zVYcxDAZE=; b=SaYlZuzBk7t3JDGvqDRhzGaE0vdvZMaZODx12H+69hYNFu4vv5HfsORgry4xUb/SVg rnjcKbp4z7wCKLMcOn/vSV6/L1ahixoi40z4HCb6poml6tbUUWWQEwQHADprrIqrWYm7 l2Wyv6GjaPjUJdnC5/hYxpSOaD4miVHCVPJyWnlhkd+pGyHiM+byiJVG/rdpPDa5ur6B qPjM1GudX788jsiGDty8OMroxPP4lKD5mwqasbV0bEON8L3UA8csdV23reizaIowJC+0 bsZk8vH1/rEjsJfJ+2by2jOO7xENT0n1P6b5r1SWan5+uB9NkmgrgwQTs3h1rPqQieB2 jsBw== X-Gm-Message-State: AOAM533Ws47Q97pyz5ATHEost/aLc+2emJTPW7Q2gcFB9h1eCp9dkxUX MAAc0Ab7EyXkW/cq5rTnWosNyLyK348= X-Google-Smtp-Source: ABdhPJyB+k+E1/hwGh/s24dEG0E2+0GMIoNZqfTfyQDtIAa5MHeRRxPIYm1cBoQryvT50ri5jVCOZA== X-Received: by 2002:a63:6ca:: with SMTP id 193mr33710577pgg.265.1629756488857; Mon, 23 Aug 2021 15:08:08 -0700 (PDT) From: G S Niteesh Babu To: qemu-devel@nongnu.org Subject: [PATCH v6 3/5] python: Add entry point for aqmp-tui Date: Tue, 24 Aug 2021 03:37:44 +0530 Message-Id: <20210823220746.28295-4-niteesh.gs@gmail.com> X-Mailer: git-send-email 2.17.1 In-Reply-To: <20210823220746.28295-1-niteesh.gs@gmail.com> References: <20210823220746.28295-1-niteesh.gs@gmail.com> Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2607:f8b0:4864:20::436; envelope-from=niteesh.gs@gmail.com; helo=mail-pf1-x436.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, FREEMAIL_FROM=0.001, RCVD_IN_DNSWL_NONE=-0.0001, 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: ehabkost@redhat.com, kchamart@redhat.com, jsnow@redhat.com, armbru@redhat.com, wainersm@redhat.com, G S Niteesh Babu , stefanha@redhat.com, crosa@redhat.com, eblake@redhat.com Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1629758402284100001 Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" 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 --- python/setup.cfg | 1 + 1 file changed, 1 insertion(+) diff --git a/python/setup.cfg b/python/setup.cfg index e9ceaea637..0850c7a10f 100644 --- a/python/setup.cfg +++ b/python/setup.cfg @@ -66,6 +66,7 @@ console_scripts =3D qom-fuse =3D qemu.qmp.qom_fuse:QOMFuse.entry_point [fuse] qemu-ga-client =3D qemu.qmp.qemu_ga_client:main qmp-shell =3D qemu.qmp.qmp_shell:main + aqmp-tui =3D qemu.aqmp.aqmp_tui:main [tui] =20 [flake8] extend-ignore =3D E722 # Prefer pylint's bare-except checks to flake8's --=20 2.17.1 From nobody Sun May 5 20:29:32 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=gmail.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1629758378268211.11117818178525; Mon, 23 Aug 2021 15:39:38 -0700 (PDT) Received: from localhost ([::1]:41034 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1mIIbR-00040A-6o for importer@patchew.org; Mon, 23 Aug 2021 18:39:37 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:43216) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIIa5-0002f6-V2 for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:38:13 -0400 Received: from mail-ot1-x335.google.com ([2607:f8b0:4864:20::335]:42992) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1mIIa4-00073g-Gd for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:38:13 -0400 Received: by mail-ot1-x335.google.com with SMTP id c19-20020a9d6153000000b0051829acbfc7so40627633otk.9 for ; Mon, 23 Aug 2021 15:38:12 -0700 (PDT) Received: from localhost.localdomain ([120.138.13.180]) by smtp.gmail.com with ESMTPSA id j21sm16217454pfj.66.2021.08.23.15.08.09 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 23 Aug 2021 15:08:12 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references; bh=e+vmUdU/giGsSkSIQo4m0qZs9uEO4d8YRre5I3lw2nc=; b=kLoxJBx6V8XgYplkU2TmV5ALQojT+RLKaWrtUhuQEbxLD1rssDPPGPKtoj746L8Fdi DgSeCbMKz+XZUtOksJKgNlupq4MIw7O+u44uM2fePg3trQ0OUoPFxjnWj1e1iVDKZ0CD WPgVnBeVADD39y9135K+J67kYsVCLVbWlUWWpUoSTgdsFA3nVgbYbbva6Kstfv+vHAMB mURVeuBVs58jdWeiSoo3lPnVNpU8NO02kO3ooOSkBAy3yMnYJfAROCN8L/Lk2kvmhkOh zik6mTR/1GQgX8EtdpcuXyn5od6nmlwsh+SoIjNL+OIs+DetmnaUK8VJDD8X2qCutU/Y CJjw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references; bh=e+vmUdU/giGsSkSIQo4m0qZs9uEO4d8YRre5I3lw2nc=; b=SfwxRVQZungrKazVyrfa4Tg0NyekddYKFT6em2mpeJA41Pt0jntKwrOCZA21HeaQu9 woiExNbT5aRO+EIhcntJtYe90MIOlzhIPR3zXelly8FPwt+wEm7+Xxv4qt5PWtlynkXn jwmgw3bk5aK/M0k530AJpm9g/lUYXvTGEfBcZYKuLCLpqfkKmCyLZGxeVyPeqJZVcetZ 0eeMCUrphlnzfjWrFuIWTku9uzGIxJJTUlaLjiY7B50ayBmgrBQa0aZhI/NfWUPiZ+uR Scu64n+m4+Ws43budEalWcg/jVQUxLlt8PVYAc0dijVOKbvK3bR4fMSr66WxaUi/VWo7 1xnw== X-Gm-Message-State: AOAM531piUDUc3FcGhh4uVCT9Bc+2SMiTG3LI3eI6+u9JH36TmZ3ujK3 jEVJmb/VHyuwUJZ4FEe34tk2GVpaSuc= X-Google-Smtp-Source: ABdhPJwc/Ww+SS2rHLLZM3AtRrY9wd0iFRt+fgZAWOepyqAtGpUYfcwCLclc9W0vPgmAaD58thnWWg== X-Received: by 2002:a17:90a:4b4d:: with SMTP id o13mr738688pjl.236.1629756492895; Mon, 23 Aug 2021 15:08:12 -0700 (PDT) From: G S Niteesh Babu To: qemu-devel@nongnu.org Subject: [PATCH v6 4/5] python: add optional pygments dependency Date: Tue, 24 Aug 2021 03:37:45 +0530 Message-Id: <20210823220746.28295-5-niteesh.gs@gmail.com> X-Mailer: git-send-email 2.17.1 In-Reply-To: <20210823220746.28295-1-niteesh.gs@gmail.com> References: <20210823220746.28295-1-niteesh.gs@gmail.com> Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2607:f8b0:4864:20::335; envelope-from=niteesh.gs@gmail.com; helo=mail-ot1-x335.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, FREEMAIL_FROM=0.001, RCVD_IN_DNSWL_NONE=-0.0001, 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: ehabkost@redhat.com, kchamart@redhat.com, jsnow@redhat.com, armbru@redhat.com, wainersm@redhat.com, G S Niteesh Babu , stefanha@redhat.com, crosa@redhat.com, eblake@redhat.com Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1629758378900100001 Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" 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 --- 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": "=3D=3D2.0.0" }, + "pygments": { + "hashes": [ + "sha256:a18f47b506a429f6f4b9df81bb02beab9ca21d0a5fee38ed15= aef65f0545519f", + "sha256:d66e804411278594d764fc69ec36ec13d9ae9147193a1740cd= 34d272ca383b8e" + ], + "markers": "python_version >=3D '3.5'", + "version": "=3D=3D2.9.0" + }, "pylint": { "hashes": [ "sha256:082a6d461b54f90eea49ca90fff4ee8b6e45e8029e5dbd72f6= 107ef84f3779c0", diff --git a/python/setup.cfg b/python/setup.cfg index 0850c7a10f..435f86384a 100644 --- a/python/setup.cfg +++ b/python/setup.cfg @@ -46,6 +46,7 @@ devel =3D tox >=3D 3.18.0 urwid >=3D 2.1.2 urwid-readline >=3D 0.13 + Pygments >=3D 2.9.0 =20 # Provides qom-fuse functionality fuse =3D @@ -55,6 +56,7 @@ fuse =3D tui =3D urwid >=3D 2.1.2 urwid-readline >=3D 0.13 + Pygments >=3D 2.9.0 =20 [options.entry_points] console_scripts =3D @@ -97,6 +99,9 @@ ignore_missing_imports =3D True [mypy-urwid_readline] ignore_missing_imports =3D True =20 +[mypy-pygments] +ignore_missing_imports =3D True + [pylint.messages control] # Disable the message, report, category or checker with the given id(s). Y= ou # can either give multiple identifiers separated by comma (,) or put this --=20 2.17.1 From nobody Sun May 5 20:29:32 2024 Delivered-To: importer@patchew.org Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=gmail.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1629758171250667.8944994356128; Mon, 23 Aug 2021 15:36:11 -0700 (PDT) Received: from localhost ([::1]:34164 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1mIIY5-0007jY-54 for importer@patchew.org; Mon, 23 Aug 2021 18:36:09 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:42692) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1mIIXL-0006y1-77 for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:35:23 -0400 Received: from mail-ot1-x32b.google.com ([2607:f8b0:4864:20::32b]:39666) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.90_1) (envelope-from ) id 1mIIXJ-0005D7-J3 for qemu-devel@nongnu.org; Mon, 23 Aug 2021 18:35:22 -0400 Received: by mail-ot1-x32b.google.com with SMTP id m7-20020a9d4c87000000b0051875f56b95so40624715otf.6 for ; Mon, 23 Aug 2021 15:35:21 -0700 (PDT) Received: from localhost.localdomain ([120.138.13.180]) by smtp.gmail.com with ESMTPSA id j21sm16217454pfj.66.2021.08.23.15.08.13 (version=TLS1_3 cipher=TLS_AES_256_GCM_SHA384 bits=256/256); Mon, 23 Aug 2021 15:08:16 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id:in-reply-to:references; bh=R7ktUvg5r97nqSMVHOdi3lwmVaZWSTvCueL6N3SYN8o=; b=kqCnqin+6I/mh/JGuUuzbVUBFlLr4wnpzHKRzNFIK2glFr3STJzQpf+t3GPsymjWhs iT/d+SKe7G7MIumMzG9M+7FrOTiw56riZFEVMxgcoybvIAe/+D1ebCvrCAH3FSFMb4yo dZKR4qKTxXQddBsuR6O2VEPqUvRV11BdVyOm3ssBVx7Lngdj0xMhUslNz3ywkJpGGYbc Cdz2jmowDYnyTDx7kUmmSHymqtvyaTndNpwFRzFMFxKoYWwx6SuMBGhk/P1a0C7oI0sg SPo7jhlY9WokSjcWrpYV+S3Ykk6jcv0Idfx8YyUzPUSJSjLnWUeqly3Pu7kap1bdc1Jc Vgyw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:from:to:cc:subject:date:message-id:in-reply-to :references; bh=R7ktUvg5r97nqSMVHOdi3lwmVaZWSTvCueL6N3SYN8o=; b=DhjHPFig1ze4kJjkburP8IWZwYKBBmfXje/Pp62Q5Onqrt35OUmWqKIgBIoaxEx0A+ Yw2YW0gGDSUMYQADAoVwwBUiIY745Xiiu371zMay8v9RysW86xfuFK10DSqhNbTymD35 aUToMxebcA10nH2SbZ0Ksu2LLJNzGuDicJmeYpothVwnY2tRCxwg1Snh+xTYADOwTxe4 9u4Um7UltAl9B1pLXmHjUTgPwkEei9SBNcfkoH/wI8P+pymci7MZZYEqDcKSO3dC6zZe PCYMz0KPfKVAfzUesL863qgVXwG2/rSk3NMHKOc+nFAKbFUcjZEiEH9Z+/YbJ2WHmpiz P5RQ== X-Gm-Message-State: AOAM533lKlgx8hJOcMbYDoyW5MErD2ShswVHKFgeXHJ5VGsL7lBTLwcX NvDCHA+8GUMDYWfbNUjmoDg5hNz9C9o= X-Google-Smtp-Source: ABdhPJwUXhfrKbrZLsPCF/5BXM7e40qGoZSYEm91Kj681cvQJ/I+6Tej1kGtfRNm/b0nixS+8nV1ww== X-Received: by 2002:a17:90a:bc47:: with SMTP id t7mr757067pjv.19.1629756496989; Mon, 23 Aug 2021 15:08:16 -0700 (PDT) From: G S Niteesh Babu To: qemu-devel@nongnu.org Subject: [PATCH v6 5/5] python/aqmp-tui: Add syntax highlighting Date: Tue, 24 Aug 2021 03:37:46 +0530 Message-Id: <20210823220746.28295-6-niteesh.gs@gmail.com> X-Mailer: git-send-email 2.17.1 In-Reply-To: <20210823220746.28295-1-niteesh.gs@gmail.com> References: <20210823220746.28295-1-niteesh.gs@gmail.com> Received-SPF: pass (zohomail.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Received-SPF: pass client-ip=2607:f8b0:4864:20::32b; envelope-from=niteesh.gs@gmail.com; helo=mail-ot1-x32b.google.com X-Spam_score_int: -20 X-Spam_score: -2.1 X-Spam_bar: -- X-Spam_report: (-2.1 / 5.0 requ) BAYES_00=-1.9, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, FREEMAIL_FROM=0.001, RCVD_IN_DNSWL_NONE=-0.0001, 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: ehabkost@redhat.com, kchamart@redhat.com, jsnow@redhat.com, armbru@redhat.com, wainersm@redhat.com, G S Niteesh Babu , stefanha@redhat.com, crosa@redhat.com, eblake@redhat.com Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1629758174167100001 Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" 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 --- 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 ac533541d2..a2929f771c 100644 --- a/python/qemu/aqmp/aqmp_tui.py +++ b/python/qemu/aqmp/aqmp_tui.py @@ -30,6 +30,8 @@ cast, ) =20 +from pygments import lexers +from pygments import token as Token import urwid import urwid_readline =20 @@ -45,6 +47,22 @@ UPDATE_MSG: str =3D 'UPDATE_MSG' =20 =20 +palette =3D [ + (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 valid/invalid multi-line JSON message into a single-line messa= ge. @@ -353,6 +371,9 @@ def run(self, debug: bool =3D False) -> None: :param debug: Enables/Disables asyncio event loop debugging """ + screen =3D urwid.raw_display.Screen() + screen.set_terminal_properties(256) + self.aloop =3D asyncio.get_event_loop() self.aloop.set_debug(debug) =20 @@ -364,6 +385,8 @@ def run(self, debug: bool =3D False) -> None: event_loop =3D urwid.AsyncioEventLoop(loop=3Dself.aloop) main_loop =3D urwid.MainLoop(urwid.AttrMap(self.window, 'backgroun= d'), unhandled_input=3Dself.unhandled_input, + screen=3Dscreen, + palette=3Dpalette, handle_mouse=3DTrue, event_loop=3Devent_loop) =20 @@ -487,7 +510,8 @@ def __init__(self, parent: App) -> None: self.history =3D urwid.SimpleFocusListWalker([]) super().__init__(self.history) =20 - 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 append= ed message. @@ -531,10 +555,18 @@ def cb_add_to_history(self, msg: str, level: Optional= [str] =3D None) -> None: =20 :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 =3D [] if level: msg =3D f'[{level}]: {msg}' - self.history.add_to_history(msg) + formatted.append((level, msg)) + else: + lexer =3D lexers.JsonLexer() # pylint: disable=3Dno-member + for token in lexer.get_tokens(msg): + formatted.append(token) + self.history.add_to_history(formatted) =20 =20 class Window(urwid.Frame): --=20 2.17.1