From nobody Tue Apr 16 17:08:32 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 1488912807008286.28219782037513; Tue, 7 Mar 2017 10:53:27 -0800 (PST) Received: from lists.phx.ovirt.org (localhost [127.0.0.1]) by lists.ovirt.org (Postfix) with ESMTP id 0F98D8204E8; Tue, 7 Mar 2017 18:53:21 +0000 (UTC) Received: from mail-qk0-f173.google.com (mail-qk0-f173.google.com [209.85.220.173]) by lists.ovirt.org (Postfix) with ESMTPS id 7942882052A for ; Tue, 7 Mar 2017 18:52:52 +0000 (UTC) Received: by mail-qk0-f173.google.com with SMTP id p64so19478625qke.1 for ; Tue, 07 Mar 2017 10:52:52 -0800 (PST) Received: from arthas.br.ibm.com ([32.104.18.201]) by smtp.gmail.com with ESMTPSA id s71sm535000qkl.60.2017.03.07.10.52.49 (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128); Tue, 07 Mar 2017 10:52:50 -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:in-reply-to:references; bh=OMdKBxcJWreAT4bAPol+iY91gcKGTmyW/4uH6pPn1m4=; b=OSO86IzQCRYjvTUjTNAPIYmUIkAyTZFGe2EuMs/gaOtsNLFgg3k4kzWb/+o5MP57eN knPsXRQn0UKOoCwC4ubWUli5Xjo9k9gORhyxs6LP1UN1rv3zEggSAAg1+u3v8Zn0swlc Bl4lhDp1HIxcqc3RshdZpcvjsb2nliqS8Wo762IKLsaSYib4ncRNtZaocGpYRXxKhWF4 U1Kb/tjJK86nFnBZINkC3CH4aKdZfOKL0mAYDn0EOummCVxaDxqJb3ncvq78Q3FtmDhb Qg0oAjrLnuSba9FuL1Mjchosd2iNW1yCTaULoGLv7KLEWNyQPzaSothdy647KMb1/zWN /B9A== 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=OMdKBxcJWreAT4bAPol+iY91gcKGTmyW/4uH6pPn1m4=; b=ufoed+segctY5rskVyqgcUoHQLBXxEFXUL3wVVE1lSo56w7tiJ2OpvfUYGTJhWV4QY pHZOA5b+bBN9cr5F/nyF6QBaSrOFNy1DFxEPEmpxBK1jDduLuBuvmWDJAIs58CV83W24 tQDauVXP62pIC5y0OMmvpGFIT6/PXBDOo9ObwigcE9+CNQV3AeGCjb8uE6ot5d4p+Vz5 abS03uTXr/5QyV943z5nO0gJoGNPCbo4nf6T8eA8z7NPvoRaicYXU/y163L1iYppjA+b HsOu/vk/H5LU9pRNAog/D/oivFvf2OtQeeURtP2h+vprjZLkxFAfA0jBHWBFxI8F4C/8 63nQ== X-Gm-Message-State: AFeK/H2t8BZ5bw/vAeYc93lcJIZIK5EBJsWQl/y8Jn5krpxvEdzMKEMTHGW0xx2WtY8gBQ== X-Received: by 10.55.15.217 with SMTP id 86mr2515284qkp.102.1488912771315; Tue, 07 Mar 2017 10:52:51 -0800 (PST) From: To: Kimchi Devel Date: Tue, 7 Mar 2017 15:52:46 -0300 Message-Id: <20170307185246.21301-2-dhbarboza82@gmail.com> X-Mailer: git-send-email 2.9.3 In-Reply-To: <20170307185246.21301-1-dhbarboza82@gmail.com> References: <20170307185246.21301-1-dhbarboza82@gmail.com> 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/user//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. A change were made in Wok base control classes to allow every call of log_request to also send a websocket notification in the following format: :/// For example, creating a new user in Ginger would trigger the following websocket notification: 'POST:/ginger/users' - 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. Changes were made in the UI of the User Log feature to refresh the listing each time a new log entry websocket notification is received. The idea is to allow this code to be a working example of how other tabs can consume the asynchronous notifications. Signed-off-by: Daniel Henrique Barboza --- contrib/DEBIAN/control.in | 1 + contrib/wok.spec.fedora.in | 1 + contrib/wok.spec.suse.in | 1 + docs/fedora-deps.md | 2 +- docs/opensuse-deps.md | 3 +- docs/ubuntu-deps.md | 3 +- src/wok/config.py.in | 8 ++ src/wok/control/base.py | 16 ++-- src/wok/model/notifications.py | 2 +- src/wok/pushserver.py | 163 +++++++++++++++++++++++++++++++++++++= ++++ src/wok/reqlogger.py | 11 ++- src/wok/root.py | 3 + src/wok/server.py | 13 +++- src/wok/websocket.py | 123 +++++++++++++++++++++++++++++++ ui/js/src/wok.main.js | 43 +++++++++++ ui/js/wok.user-log.js | 12 +++ 16 files changed, 391 insertions(+), 14 deletions(-) create mode 100644 src/wok/pushserver.py create mode 100644 src/wok/websocket.py diff --git a/contrib/DEBIAN/control.in b/contrib/DEBIAN/control.in index ba083b3..e825368 100644 --- a/contrib/DEBIAN/control.in +++ b/contrib/DEBIAN/control.in @@ -16,6 +16,7 @@ Depends: python-cherrypy3 (>=3D 3.2.0), fonts-font-awesome, logrotate, openssl, + websockify, texlive-fonts-extra Build-Depends: xsltproc, gettext, diff --git a/contrib/wok.spec.fedora.in b/contrib/wok.spec.fedora.in index 6af8222..7514376 100644 --- a/contrib/wok.spec.fedora.in +++ b/contrib/wok.spec.fedora.in @@ -21,6 +21,7 @@ Requires: fontawesome-fonts Requires: open-sans-fonts Requires: logrotate Requires: openssl +Requires: python-websockify BuildRequires: gettext-devel BuildRequires: libxslt BuildRequires: python-lxml diff --git a/contrib/wok.spec.suse.in b/contrib/wok.spec.suse.in index db31616..cca3186 100644 --- a/contrib/wok.spec.suse.in +++ b/contrib/wok.spec.suse.in @@ -22,6 +22,7 @@ Requires: fontawesome-fonts Requires: google-opensans-fonts Requires: logrotate Requires: openssl +Requires: python-websockify BuildRequires: gettext-tools BuildRequires: libxslt-tools BuildRequires: python-lxml diff --git a/docs/fedora-deps.md b/docs/fedora-deps.md index 260390e..29b477f 100644 --- a/docs/fedora-deps.md +++ b/docs/fedora-deps.md @@ -28,7 +28,7 @@ Runtime Dependencies $ sudo yum install python-cherrypy python-cheetah PyPAM m2crypto \ python-jsonschema python-psutil python-ldap \ python-lxml nginx openssl open-sans-fonts \ - fontawesome-fonts logrotate + fontawesome-fonts logrotate python-websockify =20 # For RHEL systems, install the additional packages: $ sudo yum install python-ordereddict diff --git a/docs/opensuse-deps.md b/docs/opensuse-deps.md index 7fe1763..a6086da 100644 --- a/docs/opensuse-deps.md +++ b/docs/opensuse-deps.md @@ -18,7 +18,8 @@ Runtime Dependencies $ sudo zypper install python-CherryPy python-Cheetah python-pam \ python-M2Crypto python-jsonschema python-psutil \ python-ldap python-lxml python-xml nginx openssl= \ - google-opensans-fonts fontawesome-fonts logrotate + google-opensans-fonts fontawesome-fonts logrotat= e \ + python-websockify =20 Packages required for UI development ------------------------------------ diff --git a/docs/ubuntu-deps.md b/docs/ubuntu-deps.md index 3a0f75c..cdffc59 100644 --- a/docs/ubuntu-deps.md +++ b/docs/ubuntu-deps.md @@ -18,7 +18,8 @@ Runtime Dependencies $ sudo apt-get install python-cherrypy3 python-cheetah python-pam \ python-m2crypto python-jsonschema \ python-psutil python-ldap python-lxml nginx \ - openssl fonts-font-awesome texlive-fonts-extra + openssl fonts-font-awesome texlive-fonts-extra= \ + websockify =20 Packages required for UI development ------------------------------------ diff --git a/src/wok/config.py.in b/src/wok/config.py.in index 97776dd..677d0ed 100644 --- a/src/wok/config.py.in +++ b/src/wok/config.py.in @@ -66,10 +66,18 @@ def get_object_store(): return os.path.join(paths.state_dir, 'objectstore') =20 =20 +def get_pushserver_socket_dir(): + return '/run/user/%s' % os.geteuid() + + def get_version(): return "-".join([__version__, __release__]) =20 =20 +def get_wstokens_dir(): + return os.path.join(paths.state_dir, 'ws-tokens') + + class Paths(object): =20 def __init__(self): diff --git a/src/wok/control/base.py b/src/wok/control/base.py index 0791062..b534b6f 100644 --- a/src/wok/control/base.py +++ b/src/wok/control/base.py @@ -163,7 +163,9 @@ class Resource(object): # log request code =3D self.getRequestMessage(method, action_name) reqParams =3D utf8_dict(self.log_args, request) - log_id =3D log_request(code, reqParams, details, method, s= tatus) + log_id =3D log_request(code, reqParams, details, method, s= tatus, + class_name=3Dget_class_name(self), + action_name=3Daction_name) if status =3D=3D 202: save_request_log_id(log_id, action_result['id']) =20 @@ -218,7 +220,8 @@ class Resource(object): # log request if method not in LOG_DISABLED_METHODS and status !=3D 202: code =3D self.getRequestMessage(method) - log_request(code, self.log_args, details, method, status) + log_request(code, self.log_args, details, method, status, + class_name=3Dget_class_name(self)) =20 return result =20 @@ -306,7 +309,8 @@ class AsyncResource(Resource): code =3D self.getRequestMessage(method) reqParams =3D utf8_dict(self.log_args) log_id =3D log_request(code, reqParams, None, method, - cherrypy.response.status) + cherrypy.response.status, + class_name=3Dget_class_name(self)) save_request_log_id(log_id, task['id']) =20 return wok.template.render("Task", task) @@ -458,7 +462,8 @@ class Collection(object): # log request code =3D self.getRequestMessage(method) reqParams =3D utf8_dict(self.log_args, params) - log_request(code, reqParams, details, method, status) + log_request(code, reqParams, details, method, status, + class_name=3Dget_class_name(self)) =20 =20 class AsyncCollection(Collection): @@ -486,7 +491,8 @@ class AsyncCollection(Collection): code =3D self.getRequestMessage(method) reqParams =3D utf8_dict(self.log_args, params) log_id =3D log_request(code, reqParams, None, method, - cherrypy.response.status) + cherrypy.response.status, + class_name=3Dget_class_name(self)) save_request_log_id(log_id, task['id']) =20 return wok.template.render("Task", task) diff --git a/src/wok/model/notifications.py b/src/wok/model/notifications.py index bdb7c78..f4eb542 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 diff --git a/src/wok/pushserver.py b/src/wok/pushserver.py new file mode 100644 index 0000000..4e89f36 --- /dev/null +++ b/src/wok/pushserver.py @@ -0,0 +1,163 @@ +# +# 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 wok.websocket as websocket +from wok.config import get_pushserver_socket_dir +from wok.utils import wok_log + + +BASE_DIRECTORY =3D get_pushserver_socket_dir() +TOKEN_NAME =3D 'woknotifications' +END_OF_MESSAGE_MARKER =3D '//EOM//' +push_server =3D None + + +def start_push_server(): + global push_server + + if not push_server: + push_server =3D PushServer() + + +def send_websocket_notification(message): + global push_server + + if push_server: + push_server.send_notification(message) + + +def send_wok_notification(uri, entity, method, action_name=3DNone): + app_name =3D 'wok' + app =3D cherrypy.tree.apps.get(uri) + if app: + app_name =3D app.root.domain + + source =3D '/%s/%s' % (app_name, entity) + if action_name: + source =3D '%s/%s' % (source, action_name) + message =3D '%s:%s' % (method, source) + send_websocket_notification(message) + + +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): + message +=3D END_OF_MESSAGE_MARKER + 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..02cd1d1 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.pushserver import send_wok_notification from wok.stringutils import ascii_dict from wok.utils import remove_old_files =20 @@ -68,9 +69,11 @@ 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): + ip=3DNone, class_name=3DNone, action_name=3DNone): ''' Add an entry to user request log =20 @@ -114,6 +117,10 @@ def log_request(code, params, exception, method, statu= s, app=3DNone, user=3DNone, ip=3Dip ).log() =20 + if class_name: + send_wok_notification(app, class_name, method, action_name) + send_wok_notification('', 'logs', 'POST') + return log_id =20 =20 diff --git a/src/wok/root.py b/src/wok/root.py index ea88c8c..cb7c24e 100644 --- a/src/wok/root.py +++ b/src/wok/root.py @@ -34,6 +34,7 @@ from wok.control import sub_nodes from wok.control.base import Resource from wok.control.utils import parse_request, validate_params from wok.exception import OperationFailed, UnauthorizedError, WokException +from wok.pushserver import send_wok_notification from wok.reqlogger import log_request =20 =20 @@ -235,6 +236,7 @@ class WokRoot(Root): status =3D e.getHttpStatusCode() raise cherrypy.HTTPError(401, e.message) finally: + send_wok_notification('', 'login', 'POST') log_request(code, params, details, method, status) =20 return json.dumps(user_info) @@ -247,6 +249,7 @@ class WokRoot(Root): =20 auth.logout() =20 + send_wok_notification('', 'logout', 'POST') log_request(code, params, None, method, 200, user=3Dparams['userna= me']) =20 return '{}' diff --git a/src/wok/server.py b/src/wok/server.py index b411012..1bd7b08 100644 --- a/src/wok/server.py +++ b/src/wok/server.py @@ -25,13 +25,13 @@ 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 from wok.model import model from wok.proxy import check_proxy_config +from wok.pushserver import start_push_server from wok.reqlogger import RequestLogger from wok.root import WokRoot from wok.safewatchedfilehandler import SafeWatchedFileHandler @@ -77,7 +77,8 @@ class Server(object): os.path.abspath(configParser.get("logging", "log_dir")), os.path.dirname(os.path.abspath(options.access_log)), os.path.dirname(os.path.abspath(options.error_log)), - os.path.dirname(os.path.abspath(config.get_object_store())) + os.path.dirname(os.path.abspath(config.get_object_store())), + os.path.abspath(config.get_wstokens_dir()) ] for directory in make_dirs: if not os.path.isdir(directory): @@ -160,9 +161,15 @@ class Server(object): cherrypy.tree.mount(WokRoot(model.Model(), dev_env), options.server_root, self.configObj) =20 + self._start_websocket_server() self._load_plugins() cherrypy.lib.sessions.init() =20 + def _start_websocket_server(self): + start_push_server() + ws_proxy =3D websocket.new_ws_proxy() + cherrypy.engine.subscribe('exit', ws_proxy.terminate) + def _load_plugins(self): for plugin_name, plugin_config in get_enabled_plugins(): load_plugin(plugin_name, plugin_config) diff --git a/src/wok/websocket.py b/src/wok/websocket.py new file mode 100644 index 0000000..46d5409 --- /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, get_wstokens_dir + + +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 get_wstokens_dir() + + +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 c8c3889..b58706d 100644 --- a/ui/js/src/wok.main.js +++ b/ui/js/src/wok.main.js @@ -29,6 +29,46 @@ wok.getConfig(function(result) { wok.config =3D {}; }); =20 +wok.notificationListeners =3D []; +wok.addNotificationListener =3D function(func) { + wok.notificationListeners.push(func); + $(window).one("hashchange", function() { + var del_index =3D wok.notificationListeners.indexOf(func); + wok.notificationListeners.splice(del_index, 1); + }); +}; + +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 buffer_rcv =3D window.atob(event.data); + var messages =3D buffer_rcv.split("//EOM//"); + for (var i =3D 0; i < messages.length; i++) { + if (messages[i] =3D=3D=3D "") { + continue; + } + for (var j =3D 0; j < wok.notificationListeners.length; j++) { + wok.notificationListeners[j](messages[i]); + } + } + }; + + 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 +435,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..765b75a 100644 --- a/ui/js/wok.user-log.js +++ b/ui/js/wok.user-log.js @@ -153,6 +153,18 @@ wok.initUserLogContent =3D function() { $("#user-log-grid").bootgrid("search"); wok.initUserLogConfigGridData(); }); + + wok.addNotificationListener(function(message) { + var msg_attr =3D message.split(":"); + if (msg_attr.length !=3D 2) { + return; + } + var method =3D msg_attr[0]; + var target =3D msg_attr[1]; + if (method =3D=3D=3D "POST" && target =3D=3D=3D '/wok/logs') { + $("#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