From nobody Thu Apr 25 10:23:55 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of ovirt.org designates 66.187.230.42 as permitted sender) client-ip=66.187.230.42; envelope-from=kimchi-devel-bounces@ovirt.org; helo=lists.ovirt.org; Authentication-Results: mx.zoho.com; spf=pass (zoho.com: domain of ovirt.org designates 66.187.230.42 as permitted sender) smtp.mailfrom=kimchi-devel-bounces@ovirt.org; Return-Path: Received: from lists.ovirt.org (lists.phx.ovirt.org [66.187.230.42]) by mx.zohomail.com with SMTPS id 1487942575118948.5288806709356; Fri, 24 Feb 2017 05:22:55 -0800 (PST) Received: from lists.phx.ovirt.org (localhost [127.0.0.1]) by lists.ovirt.org (Postfix) with ESMTP id 90DEB820582; Fri, 24 Feb 2017 13:22:51 +0000 (UTC) Received: from mail-qt0-f173.google.com (mail-qt0-f173.google.com [209.85.216.173]) by lists.ovirt.org (Postfix) with ESMTPS id 17119820437 for ; Fri, 24 Feb 2017 13:22:22 +0000 (UTC) Received: by mail-qt0-f173.google.com with SMTP id n21so16331990qta.1 for ; Fri, 24 Feb 2017 05:22:22 -0800 (PST) Received: from arthas.ltc.br.ibm.com ([187.113.151.243]) by smtp.gmail.com with ESMTPSA id 30sm4790766qtr.38.2017.02.24.05.22.19 (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128); Fri, 24 Feb 2017 05:22:20 -0800 (PST) X-Original-To: kimchi-devel@ovirt.org DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=from:to:cc:subject:date:message-id; bh=uAgcoVLBISJXGi0SWcYF2cbCtvs+ZwOJBuI2ejQ3Ugo=; b=DxuNyf/naGvmAe/U2vNFc+Oys8GzdpqxKakc37NkoJ3kE8NRrnFk7pwn5awVvBpZQI E1mGMgncq2LXK2qHB6GUGQxXDfFgxtpEtcnYIFpxgbWqc7rwiBj/+XyHbcU0j03893yb U3jOeY6ATcY5v7UDAJyoLU5WSAfcDIJfAjQ2/JC+OXVz5A2PVSSw2M5OA5ibm1gVu+mm C6udPewYyzuwqNP+jY7rCuok9yHP2Yu1GDk0ibYSKPB0tJ7wB0/1Wq++WtKWLIxNzpqK feUskEh+zVSw33LaJp9bvfc+8R6gZ/r25A2bMZ9NPCxTmcGjwg6omJoJR9P0NFrk+e3C vRNw== 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; bh=uAgcoVLBISJXGi0SWcYF2cbCtvs+ZwOJBuI2ejQ3Ugo=; b=EGh0UC2A6gG9ZZ2UYtD5I7LdjCvdW13aQrHwGH4UvWSUHchh0YdJ2KRfPlpxz7Fe+4 psOOzWvY3Onqz/o8wukeMUHMotRm/AdycKU+9WGHG9AnD076YucoproHtKFtzVSWr1aZ 6f6d4CuOefwvUjKyKTLINJjk9nak9OgZ9Wo6yeoTuLq8PYiSswM3fG143Swm2ytsay46 Igcgbr1z/DB7Vs5YbpkMeTx58VQusyR/xHPH9+VxHEKUoUip51ze67FCWeGJdlcrB76R j70e8DoOybKWwWpBduV6cs1wgohn8m5LgttnsUAVlTAgfTpYKSOWqHnS8G0BV6vZ5jcR knUw== X-Gm-Message-State: AMke39ljxCKOP1pdd008IU7WVxLHbj6pBl5El28AC5GwSD3dnvE8ShYoTYepLAhAcGbCpw== X-Received: by 10.200.45.112 with SMTP id o45mr2684061qta.92.1487942540762; Fri, 24 Feb 2017 05:22:20 -0800 (PST) From: To: Kimchi Devel Date: Fri, 24 Feb 2017 10:22:02 -0300 Message-Id: <20170224132202.31465-1-dhbarboza82@gmail.com> X-Mailer: git-send-email 2.9.3 Subject: [Kimchi-devel] [PATCH] [WoK] Asynchronous UI notification implementation X-BeenThere: kimchi-devel@ovirt.org X-Mailman-Version: 2.1.12 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Sender: kimchi-devel-bounces@ovirt.org Errors-To: kimchi-devel-bounces@ovirt.org X-ZohoMail: RSF_0 Z_629925259 SPT_0 Content-Type: text/plain; charset="utf-8" From: Daniel Henrique Barboza This patch makes backend and UI changes to implement the asynchronous UI notification in WoK. - Backend: A push server was implemented from scratch to manage the opened websocket connections. The push server connects to the /run/woknotifications UNIX socket and broadcasts all messages to all connections. The websocket module is the same module that exists in the Kimchi plug-in. The idea is to remove the module from Kimchi and make it use the module from WoK. ws_proxy initialization was also added in src/wok/server.py. - Frontend: In ui/js/wok.main.js two new functions were added to help the usage of asynchronous notifications in the frontend. The idea: a single websocket is opened per session. This opened websocket will broadcast all incoming messages to all listeners registered. Listeners can be added by the new wok.addNotificationListener() method. This method will clean up any registered listener by itself when the user changes tabs/URL. The single websocket sends heartbeats to the backend side each 30 seconds. No reply from the backend is issued or expected. This heartbeat is just a way to ensure that the browser does not close the connection due to inactivity. This behavior varies from browser to browser but this 30 second heartbeat is more than enough to ensure that the websocket is kept alive. - Working example in User Log: A simple usage is provided in this patch. A change was made in src/wok/reqlogger.py to send an asynchronous notification each time a new log entry is created. In ui/js/wok.user-log.js a websocket listener is added using wok.addNotificationListener() and, for each message that indicates a new user log entry, a refresh in the listing is issued. Signed-off-by: Daniel Henrique Barboza --- src/wok/model/notifications.py | 18 +++++- src/wok/pushserver.py | 132 +++++++++++++++++++++++++++++++++++++= ++++ src/wok/reqlogger.py | 7 ++- src/wok/server.py | 8 ++- src/wok/websocket.py | 123 ++++++++++++++++++++++++++++++++++++++ ui/js/src/wok.main.js | 38 ++++++++++++ ui/js/wok.user-log.js | 6 ++ 7 files changed, 327 insertions(+), 5 deletions(-) create mode 100644 src/wok/pushserver.py create mode 100644 src/wok/websocket.py diff --git a/src/wok/model/notifications.py b/src/wok/model/notifications.py index bdb7c78..597eac5 100644 --- a/src/wok/model/notifications.py +++ b/src/wok/model/notifications.py @@ -1,7 +1,7 @@ # # Project Wok # -# Copyright IBM Corp, 2016 +# Copyright IBM Corp, 2016-2017 # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -19,12 +19,22 @@ =20 from datetime import datetime =20 +from wok import config from wok.exception import NotFoundError, OperationFailed from wok.message import WokMessage +from wok.pushserver import PushServer from wok.utils import wok_log =20 =20 notificationsStore =3D {} +push_server =3D None + + +def send_websocket_notification(message): + global push_server + + if push_server: + push_server.send_notification(message) =20 =20 def add_notification(code, args=3DNone, plugin_name=3DNone): @@ -57,7 +67,11 @@ def del_notification(code): =20 class NotificationsModel(object): def __init__(self, **kargs): - pass + global push_server + + test_mode =3D config.config.get('server', 'test').lower() =3D=3D '= true' + if not test_mode: + push_server =3D PushServer() =20 def get_list(self): global notificationsStore diff --git a/src/wok/pushserver.py b/src/wok/pushserver.py new file mode 100644 index 0000000..8993f00 --- /dev/null +++ b/src/wok/pushserver.py @@ -0,0 +1,132 @@ +# +# Project Wok +# +# Copyright IBM Corp, 2017 +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-130= 1 USA +# + +import cherrypy +import os +import select +import socket +import threading + +import websocket +from utils import wok_log + + +BASE_DIRECTORY =3D '/run' +TOKEN_NAME =3D 'woknotifications' + + +class PushServer(object): + + def set_socket_file(self): + if not os.path.isdir(BASE_DIRECTORY): + try: + os.mkdir(BASE_DIRECTORY) + except OSError: + raise RuntimeError('PushServer base UNIX socket dir %s ' + 'not found.' % BASE_DIRECTORY) + + self.server_addr =3D os.path.join(BASE_DIRECTORY, TOKEN_NAME) + + if os.path.exists(self.server_addr): + try: + os.remove(self.server_addr) + except: + raise RuntimeError('There is an existing connection in %s'= % + self.server_addr) + + def __init__(self): + self.set_socket_file() + + websocket.add_proxy_token(TOKEN_NAME, self.server_addr, True) + + self.connections =3D [] + + self.server_running =3D True + self.server_socket =3D socket.socket(socket.AF_UNIX, socket.SOCK_S= TREAM) + self.server_socket.setsockopt(socket.SOL_SOCKET, + socket.SO_REUSEADDR, 1) + self.server_socket.bind(self.server_addr) + self.server_socket.listen(10) + wok_log.info('Push server created on address %s' % self.server_add= r) + + self.connections.append(self.server_socket) + cherrypy.engine.subscribe('stop', self.close_server, 1) + + server_loop =3D threading.Thread(target=3Dself.listen) + server_loop.start() + + def listen(self): + try: + while self.server_running: + read_ready, _, _ =3D select.select(self.connections, + [], [], 1) + for sock in read_ready: + if not self.server_running: + break + + if sock =3D=3D self.server_socket: + + new_socket, addr =3D self.server_socket.accept() + self.connections.append(new_socket) + else: + try: + data =3D sock.recv(4096) + except: + try: + self.connections.remove(sock) + except ValueError: + pass + + continue + if data and data =3D=3D 'CLOSE': + sock.send('ACK') + try: + self.connections.remove(sock) + except ValueError: + pass + sock.close() + + except Exception as e: + raise RuntimeError('Exception ocurred in listen() of pushserve= r ' + 'module: %s' % e.message) + + def send_notification(self, message): + for sock in self.connections: + if sock !=3D self.server_socket: + try: + sock.send(message) + except IOError as e: + if 'Broken pipe' in str(e): + sock.close() + try: + self.connections.remove(sock) + except ValueError: + pass + + def close_server(self): + try: + self.server_running =3D False + self.server_socket.shutdown(socket.SHUT_RDWR) + self.server_socket.close() + os.remove(self.server_addr) + except: + pass + finally: + cherrypy.engine.unsubscribe('stop', self.close_server) diff --git a/src/wok/reqlogger.py b/src/wok/reqlogger.py index 92e155d..1b774e2 100644 --- a/src/wok/reqlogger.py +++ b/src/wok/reqlogger.py @@ -1,7 +1,7 @@ # # Project Wok # -# Copyright IBM Corp, 2016 +# Copyright IBM Corp, 2016-2017 # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public @@ -34,6 +34,7 @@ from wok.auth import USER_NAME from wok.config import get_log_download_path, paths from wok.exception import InvalidParameter, OperationFailed from wok.message import WokMessage +from wok.model.notifications import send_websocket_notification from wok.stringutils import ascii_dict from wok.utils import remove_old_files =20 @@ -68,6 +69,8 @@ WOK_REQUEST_LOGGER =3D "wok_request_logger" # AsyncTask handling ASYNCTASK_REQUEST_METHOD =3D 'TASK' =20 +NEW_LOG_ENTRY_MESSAGE =3D 'new_log_entry' + =20 def log_request(code, params, exception, method, status, app=3DNone, user= =3DNone, ip=3DNone): @@ -114,6 +117,8 @@ def log_request(code, params, exception, method, status= , app=3DNone, user=3DNone, ip=3Dip ).log() =20 + send_websocket_notification(NEW_LOG_ENTRY_MESSAGE) + return log_id =20 =20 diff --git a/src/wok/server.py b/src/wok/server.py index fc2e167..2d823c9 100644 --- a/src/wok/server.py +++ b/src/wok/server.py @@ -25,8 +25,7 @@ import logging import logging.handlers import os =20 -from wok import auth -from wok import config +from wok import auth, config, websocket from wok.config import config as configParser from wok.config import WokConfig from wok.control import sub_nodes @@ -159,6 +158,11 @@ class Server(object): cherrypy.tree.mount(WokRoot(model.Model(), dev_env), options.server_root, self.configObj) =20 + test_mode =3D config.config.get('server', 'test').lower() =3D=3D '= true' + if not test_mode: + ws_proxy =3D websocket.new_ws_proxy() + cherrypy.engine.subscribe('exit', ws_proxy.terminate) + self._load_plugins() cherrypy.lib.sessions.init() =20 diff --git a/src/wok/websocket.py b/src/wok/websocket.py new file mode 100644 index 0000000..5d7fb91 --- /dev/null +++ b/src/wok/websocket.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python2 +# +# Project Wok +# +# Copyright IBM Corp, 2017 +# +# Code derived from Project Kimchi +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-130= 1 USA + +import base64 +import errno +import os + +from multiprocessing import Process +from websockify import WebSocketProxy + +from config import config, PluginPaths + + +try: + from websockify.token_plugins import TokenFile + tokenFile =3D True +except ImportError: + tokenFile =3D False + +try: + from websockify import ProxyRequestHandler as request_proxy +except: + from websockify import WebSocketProxy as request_proxy + + +WS_TOKENS_DIR =3D os.path.join(PluginPaths('kimchi').state_dir, 'ws-tokens= ') + + +class CustomHandler(request_proxy): + + def get_target(self, target_plugin, path): + if issubclass(CustomHandler, object): + target =3D super(CustomHandler, self).get_target(target_plugin, + path) + else: + target =3D request_proxy.get_target(self, target_plugin, path) + + if target[0] =3D=3D 'unix_socket': + try: + self.server.unix_target =3D target[1] + except: + self.unix_target =3D target[1] + else: + try: + self.server.unix_target =3D None + except: + self.unix_target =3D None + return target + + +def new_ws_proxy(): + try: + os.makedirs(WS_TOKENS_DIR, mode=3D0755) + except OSError as e: + if e.errno =3D=3D errno.EEXIST: + pass + + params =3D {'listen_host': '127.0.0.1', + 'listen_port': config.get('server', 'websockets_port'), + 'ssl_only': False} + + # old websockify: do not use TokenFile + if not tokenFile: + params['target_cfg'] =3D WS_TOKENS_DIR + + # websockify 0.7 and higher: use TokenFile + else: + params['token_plugin'] =3D TokenFile(src=3DWS_TOKENS_DIR) + + def start_proxy(): + try: + server =3D WebSocketProxy(RequestHandlerClass=3DCustomHandler, + **params) + except TypeError: + server =3D CustomHandler(**params) + + server.start_server() + + proc =3D Process(target=3Dstart_proxy) + proc.start() + return proc + + +def add_proxy_token(name, port, is_unix_socket=3DFalse): + with open(os.path.join(WS_TOKENS_DIR, name), 'w') as f: + """ + From python documentation base64.urlsafe_b64encode(s) + substitutes - instead of + and _ instead of / in the + standard Base64 alphabet, BUT the result can still + contain =3D which is not safe in a URL query component. + So remove it when needed as base64 can work well without it. + """ + name =3D base64.urlsafe_b64encode(name).rstrip('=3D') + if is_unix_socket: + f.write('%s: unix_socket:%s' % (name.encode('utf-8'), port)) + else: + f.write('%s: localhost:%s' % (name.encode('utf-8'), port)) + + +def remove_proxy_token(name): + try: + os.unlink(os.path.join(WS_TOKENS_DIR, name)) + except OSError: + pass diff --git a/ui/js/src/wok.main.js b/ui/js/src/wok.main.js index 20c017e..f5031ce 100644 --- a/ui/js/src/wok.main.js +++ b/ui/js/src/wok.main.js @@ -29,6 +29,41 @@ wok.getConfig(function(result) { wok.config =3D {}; }); =20 + +wok.notificationListeners =3D {}; +wok.addNotificationListener =3D function(name, func) { + wok.notificationListeners[name] =3D func; + $(window).one("hashchange", function() { + delete wok.notificationListeners[name]; + }); +}; + +wok.notificationsWebSocket =3D undefined; +wok.startNotificationWebSocket =3D function () { + var addr =3D window.location.hostname + ':' + window.location.port; + var token =3D wok.urlSafeB64Encode('woknotifications').replace(/=3D*$/= g, ""); + var url =3D 'wss://' + addr + '/websockify?token=3D' + token; + wok.notificationsWebSocket =3D new WebSocket(url, ['base64']); + + wok.notificationsWebSocket.onmessage =3D function(event) { + var message =3D window.atob(event.data); + for (name in wok.notificationListeners) { + func =3D wok.notificationListeners[name]; + func(message); + } + }; + + sessionStorage.setItem('wokNotificationWebSocket', 'true'); + var heartbeat =3D setInterval(function() { + wok.notificationsWebSocket.send(window.btoa('heartbeat')); + }, 30000); + + wok.notificationsWebSocket.onclose =3D function() { + clearInterval(heartbeat); + }; +}; + + wok.main =3D function() { wok.isLoggingOut =3D false; wok.popable(); @@ -395,6 +430,9 @@ wok.main =3D function() { =20 // Set handler for help button $('#btn-help').on('click', wok.openHelp); + + // start WebSocket + wok.startNotificationWebSocket(); }; =20 var initUI =3D function() { diff --git a/ui/js/wok.user-log.js b/ui/js/wok.user-log.js index 0e8fb09..083b6c3 100644 --- a/ui/js/wok.user-log.js +++ b/ui/js/wok.user-log.js @@ -153,6 +153,12 @@ wok.initUserLogContent =3D function() { $("#user-log-grid").bootgrid("search"); wok.initUserLogConfigGridData(); }); + + wok.addNotificationListener('userlog', function(message) { + if (message =3D=3D=3D 'new_log_entry') { + $("#refresh-button").click(); + } + }); }; =20 wok.initUserLogWindow =3D function() { --=20 2.9.3 _______________________________________________ Kimchi-devel mailing list Kimchi-devel@ovirt.org http://lists.ovirt.org/mailman/listinfo/kimchi-devel