source: ogAgent-Git/src/OGAgentUser-qt4.py @ 6a01818

decorare-oglive-methodsfixes-winlgromero-filebeatmainmodulesnew-browserno-ptt-paramogadmcliogadmclient-statusogagent-jobsogagent-macosogcore1oglogoglog2override-moduleping1ping2ping3ping4py3-winpython3report-progresstlsunification2unification3versionswindows-fixes
Last change on this file since 6a01818 was 3910a84, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#940: Build an OGAgent for Windows Python 2-compatible.

  • Property mode set to 100644
File size: 11.7 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright (c) 2014 Virtual Cable S.L.
5# All rights reserved.
6#
7# Redistribution and use in source and binary forms, with or without modification,
8# are permitted provided that the following conditions are met:
9#
10#    * Redistributions of source code must retain the above copyright notice,
11#      this list of conditions and the following disclaimer.
12#    * Redistributions in binary form must reproduce the above copyright notice,
13#      this list of conditions and the following disclaimer in the documentation
14#      and/or other materials provided with the distribution.
15#    * Neither the name of Virtual Cable S.L. nor the names of its contributors
16#      may be used to endorse or promote products derived from this software
17#      without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29"""
30@author: Adolfo Gómez, dkmaster at dkmon dot com
31"""
32from __future__ import unicode_literals
33
34import sys
35import time
36import json
37import six
38import atexit
39from PyQt4 import QtCore, QtGui  # @UnresolvedImport
40
41from opengnsys import VERSION, ipc, operations, utils
42from opengnsys.log import logger
43from opengnsys.service import IPC_PORT
44from about_dialog_qt4_ui import Ui_OGAAboutDialog
45from message_dialog_qt4_ui import Ui_OGAMessageDialog
46from opengnsys.scriptThread import ScriptExecutorThread
47from opengnsys.config import readConfig
48from opengnsys.loader import loadModules
49
50# Set default characters encoding to UTF-8
51reload(sys)
52if hasattr(sys, 'setdefaultencoding'):
53    sys.setdefaultencoding('utf-8')
54
55trayIcon = None
56
57
58def sigAtExit():
59    if trayIcon:
60        trayIcon.quit()
61
62
63# About dialog
64class OGAAboutDialog(QtGui.QDialog):
65    def __init__(self, parent=None):
66        QtGui.QDialog.__init__(self, parent)
67        self.ui = Ui_OGAAboutDialog()
68        self.ui.setupUi(self)
69        self.ui.VersionLabel.setText("Version " + VERSION)
70
71    def closeDialog(self):
72        self.hide()
73
74
75class OGAMessageDialog(QtGui.QDialog):
76    def __init__(self, parent=None):
77        QtGui.QDialog.__init__(self, parent)
78        self.ui = Ui_OGAMessageDialog()
79        self.ui.setupUi(self)
80
81    def message(self, message):
82        self.ui.message.setText(message)
83        self.show()
84
85    def closeDialog(self):
86        self.hide()
87
88
89class MessagesProcessor(QtCore.QThread):
90    logoff = QtCore.pyqtSignal(name='logoff')
91    message = QtCore.pyqtSignal(tuple, name='message')
92    script = QtCore.pyqtSignal(QtCore.QString, name='script')
93    exit = QtCore.pyqtSignal(name='exit')
94
95    def __init__(self, port):
96        super(self.__class__, self).__init__()
97        # Retries connection for a while
98        for _ in range(10):
99            try:
100                self.ipc = ipc.ClientIPC(port)
101                self.ipc.start()
102                break
103            except Exception:
104                logger.debug('IPC Server is not reachable')
105                self.ipc = None
106                time.sleep(2)
107
108        self.running = False
109
110    def stop(self):
111        self.running = False
112        if self.ipc:
113            self.ipc.stop()
114
115    def isAlive(self):
116        return self.ipc is not None
117
118    def sendLogin(self, user_data):
119        if self.ipc:
120            self.ipc.sendLogin(user_data)
121
122    def sendLogout(self, userName):
123        if self.ipc:
124            self.ipc.sendLogout(userName)
125
126    def run(self):
127        if self.ipc is None:
128            return
129        self.running = True
130
131        # Wait a bit so we ensure IPC thread is running...
132        time.sleep(2)
133
134        while self.running and self.ipc.running:
135            try:
136                msg = self.ipc.getMessage()
137                if msg is None:
138                    break
139                msg_id, data = msg
140                logger.debug('Got Message on User Space: {}:{}'.format(msg_id, data))
141                if msg_id == ipc.MSG_MESSAGE:
142                    module, message, data = data.split('\0')
143                    self.message.emit((module, message, data))
144                elif msg_id == ipc.MSG_LOGOFF:
145                    self.logoff.emit()
146                elif msg_id == ipc.MSG_SCRIPT:
147                    self.script.emit(QtCore.QString.fromUtf8(data))
148            except Exception as e:
149                try:
150                    logger.error('Got error on IPC thread {}'.format(utils.exceptionToMessage(e)))
151                except:
152                    logger.error('Got error on IPC thread (an unicode error??)')
153
154        if self.ipc.running is False and self.running is True:
155            logger.warn('Lost connection with Service, closing program')
156
157        self.exit.emit()
158
159
160class OGASystemTray(QtGui.QSystemTrayIcon):
161    def __init__(self, app_, parent=None):
162        self.app = app_
163        self.config = readConfig(client=True)
164        self.modules = None
165
166        # Get opengnsys section as dict
167        cfg = dict(self.config.items('opengnsys'))
168
169        # Set up log level
170        logger.setLevel(cfg.get('log', 'INFO'))
171
172        self.ipcport = int(cfg.get('ipc_port', IPC_PORT))
173
174        # style = app.style()
175        # icon = QtGui.QIcon(style.standardPixmap(QtGui.QStyle.SP_ComputerIcon))
176        icon = QtGui.QIcon(':/images/img/oga.png')
177
178        QtGui.QSystemTrayIcon.__init__(self, icon, parent)
179        self.menu = QtGui.QMenu(parent)
180        exit_action = self.menu.addAction("About")
181        exit_action.triggered.connect(self.about)
182        self.setContextMenu(self.menu)
183        self.ipc = MessagesProcessor(self.ipcport)
184
185        if self.ipc.isAlive() is False:
186            raise Exception('No connection to service, exiting.')
187
188        self.timer = QtCore.QTimer()
189        self.timer.timeout.connect(self.timerFnc)
190
191        self.stopped = False
192
193        self.ipc.message.connect(self.message)
194        self.ipc.exit.connect(self.quit)
195        self.ipc.script.connect(self.executeScript)
196        self.ipc.logoff.connect(self.logoff)
197
198        self.aboutDlg = OGAAboutDialog()
199        self.msgDlg = OGAMessageDialog()
200
201        self.timer.start(1000)  # Launch idle checking every 1 seconds
202
203        self.ipc.start()
204
205    def initialize(self):
206        # Load modules and activate them
207        # Also, sends "login" event to service
208        self.modules = loadModules(self, client=True)
209        logger.debug('Modules: {}'.format(list(v.name for v in self.modules)))
210
211        # Send init to all modules
212        valid_mods = []
213        for mod in self.modules:
214            try:
215                logger.debug('Activating module {}'.format(mod.name))
216                mod.activate()
217                valid_mods.append(mod)
218            except Exception as e:
219                logger.exception()
220                logger.error("Activation of {} failed: {}".format(mod.name, utils.exceptionToMessage(e)))
221
222        self.modules[:] = valid_mods  # copy instead of assignment
223
224        # If this is running, it's because he have logged in, inform service of this fact
225        self.ipc.sendLogin((operations.getCurrentUser(), operations.getSessionLanguage(),
226                            operations.get_session_type()))
227
228    def deinitialize(self):
229        for mod in reversed(self.modules):  # Deinitialize reversed of initialization
230            try:
231                logger.debug('Deactivating module {}'.format(mod.name))
232                mod.deactivate()
233            except Exception as e:
234                logger.exception()
235                logger.error("Deactivation of {} failed: {}".format(mod.name, utils.exceptionToMessage(e)))
236
237    def timerFnc(self):
238        pass
239
240    def message(self, msg):
241        """
242        Processes the message sent asynchronously, msg is an QString
243        """
244        try:
245            logger.debug('msg: {}, {}'.format(type(msg), msg))
246            module, message, data = msg
247        except Exception as e:
248            logger.error('Got exception {} processing message {}'.format(e, msg))
249            return
250
251        for v in self.modules:
252            if v.name == module:  # Case Sensitive!!!!
253                try:
254                    logger.debug('Notifying message {} to module {} with json data {}'.format(message, v.name, data))
255                    v.processMessage(message, json.loads(data))
256                    return
257                except Exception as e:
258                    logger.error('Got exception {} processing generic message on {}'.format(e, v.name))
259
260        logger.error('Module {} not found, messsage {} not sent'.format(module, message))
261
262    def executeScript(self, script):
263        logger.debug('Executing script')
264        script = six.text_type(script.toUtf8()).decode('base64')
265        th = ScriptExecutorThread(script)
266        th.start()
267
268    def logoff(self):
269        logger.debug('Logoff invoked')
270        operations.logoff()  # Invoke log off
271
272    def about(self):
273        self.aboutDlg.exec_()
274
275    def cleanup(self):
276        logger.debug('Quit invoked')
277        if self.stopped is False:
278            self.stopped = True
279            try:
280                self.deinitialize()
281            except Exception:
282                logger.exception()
283                logger.error('Got exception deinitializing modules')
284
285            try:
286                # If we close Client, send Logoff to Broker
287                self.ipc.sendLogout(operations.getCurrentUser())
288                time.sleep(1)
289                self.timer.stop()
290                self.ipc.stop()
291            except Exception:
292                # May we have lost connection with server, simply log and exit in that case
293                logger.exception()
294                logger.exception("Got an exception, processing quit")
295
296            try:
297                # operations.logoff()  # Uncomment this after testing to logoff user
298                pass
299            except Exception:
300                pass
301
302    def quit(self):
303        # logger.debug("Exec quit {}".format(self.stopped))
304        if self.stopped is False:
305            self.cleanup()
306            self.app.quit()
307
308    def closeEvent(self, event):
309        logger.debug("Exec closeEvent")
310        event.accept()
311        self.quit()
312
313
314if __name__ == '__main__':
315    app = QtGui.QApplication(sys.argv)
316
317    if not QtGui.QSystemTrayIcon.isSystemTrayAvailable():
318        # QtGui.QMessageBox.critical(None, "Systray", "I couldn't detect any system tray on this system.")
319        sys.exit(1)
320
321    # This is important so our app won't close on messages windows (alerts, etc...)
322    QtGui.QApplication.setQuitOnLastWindowClosed(False)
323
324    try:
325        trayIcon = OGASystemTray(app)
326    except Exception as e:
327        logger.exception()
328        logger.error('OGA Service is not running, or it can\'t contact with OGA Server. User Tools stopped: {}'.format(
329            utils.exceptionToMessage(e)))
330        sys.exit(1)
331
332    try:
333        trayIcon.initialize()  # Initialize modules, etc..
334    except Exception as e:
335        logger.exception()
336        logger.error('Exception initializing OpenGnsys User Agent {}'.format(utils.exceptionToMessage(e)))
337        trayIcon.quit()
338        sys.exit(1)
339
340    app.aboutToQuit.connect(trayIcon.cleanup)
341    trayIcon.show()
342
343    # Catch kill and logout user :)
344    atexit.register(sigAtExit)
345
346    res = app.exec_()
347
348    logger.debug('Exiting')
349    trayIcon.quit()
350
351    sys.exit(res)
Note: See TracBrowser for help on using the repository browser.