Пример #1
0
    def run(self):
        self.running = True

        self.serverSocket.bind(('localhost', self.port))
        self.serverSocket.setblocking(1)
        self.serverSocket.listen(4)

        while True:
            try:
                (clientSocket, address) = self.serverSocket.accept()
                # Stop processing if thread is mean to stop
                if self.running is False:
                    break
                logger.debug('Got connection from {}'.format(address))

                self.cleanupFinishedThreads()  # House keeping

                logger.debug('Starting new thread, current: {}'.format(
                    self.threads))
                t = ClientProcessor(self, clientSocket)
                self.threads.append(t)
                t.start()
            except Exception as e:
                logger.error(
                    'Got an exception on Server ipc thread: {}'.format(e))
Пример #2
0
    def start(self):
        """
        Start the daemon
        """
        logger.debug('Starting daemon')
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = open(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if pid:
            message = "pidfile {} already exist. Daemon already running?\n".format(
                pid)
            logger.error(message)
            sys.stderr.write(message)
            sys.exit(1)

        # Start the daemon
        self.daemonize()
        try:
            self.run()
        except Exception as e:
            logger.error('Exception running process: {}'.format(e))

        if os.path.exists(self.pidfile):
            os.remove(self.pidfile)
Пример #3
0
    def run(self):
        logger.debug('** Running Daemon **')
        set_proctitle('OGAgent')

        self.initialize()

        # Call modules initialization
        # They are called in sequence, no threading is done at this point, so ensure modules onActivate always returns
        

        # *********************
        # * Main Service loop *
        # *********************
        # Counter used to check ip changes only once every 10 seconds, for
        # example
        try:
            while self.isAlive:
                # In milliseconds, will break
                self.doWait(1000)
        except (KeyboardInterrupt, SystemExit) as e:
            logger.error('Requested exit of main loop')
        except Exception as e:
            logger.exception()
            logger.error('Caught exception on main loop: {}'.format(e))

        self.terminate()

        self.notifyStop()
Пример #4
0
    def run(self):
        if self.ipc is None:
            return
        self.running = True

        # Wait a bit so we ensure IPC thread is running...
        time.sleep(2)

        while self.running and self.ipc.running:
            try:
                msg = self.ipc.getMessage()
                if msg is None:
                    break
                msgId, data = msg
                logger.debug('Got Message on User Space: {}:{}'.format(
                    msgId, data))
                if msgId == ipc.MSG_MESSAGE:
                    module, message, data = data.split('\0')
                    self.message.emit((module, message, data))
                elif msgId == ipc.MSG_LOGOFF:
                    self.logoff.emit()
                elif msgId == ipc.MSG_SCRIPT:
                    self.script.emit(QtCore.QString.fromUtf8(data))
            except Exception as e:
                try:
                    logger.error('Got error on IPC thread {}'.format(
                        utils.exceptionToMessage(e)))
                except:
                    logger.error(
                        'Got error on IPC thread (an unicode error??)')

        if self.ipc.running is False and self.running is True:
            logger.warn('Lost connection with Service, closing program')

        self.exit.emit()
Пример #5
0
    def cleanup(self):
        logger.debug('Quit invoked')
        if self.stopped is False:
            self.stopped = True
            try:
                self.deinitialize()
            except Exception:
                logger.exception()
                logger.error('Got exception deinitializing modules')

            try:
                # If we close Client, send Logoff to Broker
                self.ipc.sendLogout(operations.getCurrentUser())
                time.sleep(1)
                self.timer.stop()
                self.ipc.stop()
            except Exception:
                # May we have lost connection with server, simply log and exit in that case
                logger.exception()
                logger.exception("Got an exception, processing quit")

            try:
                # operations.logoff()  # Uncomment this after testing to logoff user
                pass
            except Exception:
                pass
Пример #6
0
    def run(self):
        self.running = True

        while self.running:
            try:
                msg = b''
                # We look for magic message header
                while self.running:  # Wait for MAGIC
                    try:
                        buf = self.clientSocket.recv(len(MAGIC) - len(msg))
                        if buf == b'':
                            self.running = False
                            break
                        msg += buf
                        if len(msg) != len(MAGIC):
                            continue  # Do not have message
                        if msg != MAGIC:  # Skip first byte an continue searchong
                            msg = msg[1:]
                            continue
                        break
                    except socket.timeout:  # Timeout is here so we can get stop thread
                        continue

                if self.running is False:
                    break

                # Now we get message basic data (msg + datalen)
                msg = bytearray(self.receiveBytes(3))

                # We have the magic header, here comes the message itself
                if msg is None:
                    continue

                msgId = msg[0]
                dataLen = msg[1] + (msg[2] << 8)
                if msgId not in (MSG_LOGOFF, MSG_MESSAGE, MSG_SCRIPT):
                    raise Exception('Invalid message id: {}'.format(msgId))

                data = self.receiveBytes(dataLen)
                if data is None:
                    continue

                self.messages.put((msgId, data))
                self.messageReceived()

            except socket.error as e:
                logger.error(
                    'Communication with server got an error: {}'.format(
                        toUnicode(e.strerror)))
                self.running = False
                return
            except Exception as e:
                tb = traceback.format_exc()
                logger.error('Error: {}, trace: {}'.format(e, tb))

        try:
            self.clientSocket.close()
        except Exception:
            pass  # If can't close, nothing happens, just end thread
Пример #7
0
 def checkSecret(self, server):
     '''
     Checks for received secret key and raise exception if it isn't valid.
     '''
     try:
         if self.random != server.headers['Authorization']:
             raise Exception('Unauthorized operation')
     except Exception as e:
         logger.error(e)
         raise Exception(e)
Пример #8
0
 def deinitialize(self):
     for mod in reversed(
             self.modules):  # Deinitialize reversed of initialization
         try:
             logger.debug('Deactivating module {}'.format(mod.name))
             mod.deactivate()
         except Exception as e:
             logger.exception()
             logger.error("Deactivation of {} failed: {}".format(
                 mod.name, utils.exceptionToMessage(e)))
Пример #9
0
 def wrapper(*args, **kwargs):
     try:
         this, path, get_params, post_params, server = args  # @UnusedVariable
         if this.random == server.headers['Authorization']:
             fnc(*args, **kwargs)
         else:
             raise Exception('Unauthorized operation')
     except Exception as e:
         logger.error(e)
         raise Exception(e)
Пример #10
0
    def daemonize(self):
        """
        do the UNIX double-fork magic, see Stevens' "Advanced
        Programming in the UNIX Environment" for details (ISBN 0201563177)
        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
        """
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError as e:
            logger.error("fork #1 error: {}".format(e))
            sys.stderr.write("fork #1 failed: {}\n".format(e))
            sys.exit(1)

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                sys.exit(0)
        except OSError as e:
            logger.error("fork #2 error: {}".format(e))
            sys.stderr.write("fork #2 failed: {}\n".format(e))
            sys.exit(1)

        # redirect standard file descriptors
        sys.stdout.flush()
        sys.stderr.flush()
        si = open(self.stdin, 'r')
        so = open(self.stdout, 'a+')
        se = open(self.stderr, 'a+', 0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as f:
            f.write("{}\n".format(pid))
Пример #11
0
    def message(self, msg):
        '''
        Processes the message sent asynchronously, msg is an QString
        '''
        try:
            logger.debug('msg: {}, {}'.format(type(msg), msg))
            module, message, data = msg
        except Exception as e:
            logger.error('Got exception {} processing message {}'.format(
                e, msg))
            return

        for v in self.modules:
            if v.name == module:  # Case Sensitive!!!!
                try:
                    logger.debug(
                        'Notifying message {} to module {} with json data {}'.
                        format(message, v.name, data))
                    v.processMessage(message, json.loads(data))
                    return
                except Exception as e:
                    logger.error(
                        'Got exception {} processing generic message on {}'.
                        format(e, v.name))

        logger.error('Module {} not found, messsage {} not sent'.format(
            module, message))
Пример #12
0
    def SvcDoRun(self):
        '''
        Main service loop
        '''
        try:
            logger.debug('running SvcDoRun')
            servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                                  servicemanager.PYS_SERVICE_STARTED,
                                  (self._svc_name_, ''))

            # call the CoInitialize to allow the registration to run in an other
            # thread
            logger.debug('Initializing com...')
            pythoncom.CoInitialize()

            # Initialize remaining service data
            self.initialize()
        except Exception:  # Any init exception wil be caught, service must be then restarted
            logger.exception()
            logger.debug('Exiting service with failure status')
            os._exit(-1)  # pylint: disable=protected-access

        # *********************
        # * Main Service loop *
        # *********************
        try:
            while self.isAlive:
                # Pumps & processes any waiting messages
                pythoncom.PumpWaitingMessages()
                win32event.WaitForSingleObject(self.hWaitStop, 1000)
        except Exception as e:
            logger.error('Caught exception on main loop: {}'.format(e))

        logger.debug('Exited main loop, deregistering SENS')

        self.terminate()  # Ends IPC servers

        self.notifyStop()
Пример #13
0
    def initialize(self):
        # Load modules and activate them
        # Also, sends "login" event to service
        self.modules = loadModules(self, client=True)
        logger.debug('Modules: {}'.format(list(v.name for v in self.modules)))

        # Send init to all modules
        validMods = []
        for mod in self.modules:
            try:
                logger.debug('Activating module {}'.format(mod.name))
                mod.activate()
                validMods.append(mod)
            except Exception as e:
                logger.exception()
                logger.error("Activation of {} failed: {}".format(
                    mod.name, utils.exceptionToMessage(e)))

        self.modules[:] = validMods  # copy instead of assignment

        # If this is running, it's because he have logged in, inform service of this fact
        self.ipc.sendLogin(operations.getCurrentUser(),
                           operations.getSessionLanguage())
Пример #14
0
 def run(self):
     try:
         logger.debug('Executing script: {}'.format(self.script))
         six.exec_(self.script, globals(), None)
     except Exception as e:
         logger.error('Error executing script: {}'.format(e))
Пример #15
0
def usage():
    sys.stderr.write("usage: {} start|stop|restart|fg|login 'username'|logout 'username'|message 'module' 'message' 'json'\n".format(sys.argv[0]))
    sys.exit(2)

if __name__ == '__main__':
    logger.setLevel('INFO')
    
    if len(sys.argv) == 5 and sys.argv[1] == 'message':
        logger.debug('Running client opengnsys')
        client = None
        try:
            client = ipc.ClientIPC(IPC_PORT)
            client.sendMessage(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]))
            sys.exit(0)
        except Exception as e:
            logger.error(e)
        

    if len(sys.argv) == 3 and sys.argv[1] in ('login', 'logout'):
        logger.debug('Running client opengnsys')
        client = None
        try:
            client = ipc.ClientIPC(IPC_PORT)
            if 'login' == sys.argv[1]:
                client.sendLogin(sys.argv[2])
                sys.exit(0)
            elif 'logout' == sys.argv[1]:
                client.sendLogout(sys.argv[2])
                sys.exit(0)
            else:
                usage()
Пример #16
0
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    if not QtGui.QSystemTrayIcon.isSystemTrayAvailable():
        # QtGui.QMessageBox.critical(None, "Systray", "I couldn't detect any system tray on this system.")
        sys.exit(1)

    # This is important so our app won't close on messages windows (alerts, etc...)
    QtGui.QApplication.setQuitOnLastWindowClosed(False)

    try:
        trayIcon = OGASystemTray(app)
    except Exception as e:
        logger.exception()
        logger.error(
            'OGA Service is not running, or it can\'t contact with OGA Server. User Tools stopped: {}'
            .format(utils.exceptionToMessage(e)))
        sys.exit(1)

    try:
        trayIcon.initialize()  # Initialize modules, etc..
    except Exception as e:
        logger.exception()
        logger.error('Exception initializing OpenGnsys User Agent {}'.format(
            utils.exceptionToMessage(e)))
        trayIcon.quit()
        sys.exit(1)

    app.aboutToQuit.connect(trayIcon.cleanup)
    trayIcon.show()
Пример #17
0
    def run(self):
        self.running = True
        self.clientSocket.setblocking(0)

        state = None
        recv_msg = None
        recv_data = None
        while self.running:
            try:
                counter = 1024
                while counter > 0:  # So we process at least the incoming queue every XX bytes readed
                    counter -= 1
                    b = self.clientSocket.recv(1)
                    if b == b'':
                        # Client disconnected
                        self.running = False
                        break
                    buf = six.byte2int(
                        b)  # Empty buffer, this is set as non-blocking
                    if state is None:
                        if buf in (REQ_MESSAGE, REQ_LOGIN, REQ_LOGOUT):
                            logger.debug('State set to {}'.format(buf))
                            state = buf
                            recv_msg = buf
                            continue  # Get next byte
                        else:
                            logger.debug('Got unexpected data {}'.format(buf))
                    elif state in (REQ_MESSAGE, REQ_LOGIN, REQ_LOGOUT):
                        logger.debug('First length byte is {}'.format(buf))
                        msg_len = buf
                        state = ST_SECOND_BYTE
                        continue
                    elif state == ST_SECOND_BYTE:
                        msg_len += buf << 8
                        logger.debug(
                            'Second length byte is {}, len is {}'.format(
                                buf, msg_len))
                        if msg_len == 0:
                            self.processRequest(recv_msg, None)
                            state = None
                            break
                        state = ST_RECEIVING
                        recv_data = b''
                        continue
                    elif state == ST_RECEIVING:
                        recv_data += six.int2byte(buf)
                        msg_len -= 1
                        if msg_len == 0:
                            self.processRequest(recv_msg, recv_data)
                            recv_data = None
                            state = None
                            break
                    else:
                        logger.debug(
                            'Got invalid message from request: {}, state: {}'.
                            format(buf, state))
            except socket.error as e:
                # If no data is present, no problem at all, pass to check messages
                pass
            except Exception as e:
                tb = traceback.format_exc()
                logger.error('Error: {}, trace: {}'.format(e, tb))

            if self.running is False:
                break

            try:
                msg = self.messages.get(block=True, timeout=1)
            except six.moves.queue.Empty:  # No message got in time @UndefinedVariable
                continue

            logger.debug('Got message {}={}'.format(msg, REV_DICT.get(msg[0])))

            try:
                m = msg[1] if msg[1] is not None else b''
                l = len(m)
                data = MAGIC + six.int2byte(
                    msg[0]) + six.int2byte(l & 0xFF) + six.int2byte(l >> 8) + m
                try:
                    self.clientSocket.sendall(data)
                except socket.error as e:
                    # Send data error
                    logger.debug(
                        'Socket connection is no more available: {}'.format(
                            e.args))
                    self.running = False
            except Exception as e:
                logger.error('Invalid message in queue: {}'.format(e))

        logger.debug('Client processor stopped')
        try:
            self.clientSocket.close()
        except Exception:
            pass  # If can't close, nothing happens, just end thread