def __init__(self, config):
     logging.debug("AgentLogicBase:: __init__() entered")
     self.wait_stop = Event()
     self.heartBitRate = config.getint("general", "heart_beat_rate")
     self.userCheckRate = config.getint("general", "report_user_rate")
     self.appRefreshRate = config.getint("general", "report_application_rate")
     self.disksRefreshRate = config.getint("general", "report_disk_usage")
     self.activeUser = ""
     self.vio = VirtIoChannel(config.get("virtio", "device"))
     self.dr = None
     self.commandHandler = None
Example #2
0
 def __init__(self, config):
     logging.debug("AgentLogicBase:: __init__() entered")
     self.wait_stop = Event()
     self.heartBitRate = config.getint("general", "heart_beat_rate")
     self.userCheckRate = config.getint("general", "report_user_rate")
     self.appRefreshRate = config.getint("general",
                                         "report_application_rate")
     self.disksRefreshRate = config.getint("general", "report_disk_usage")
     self.numCPUsCheckRate = config.getint("general", "report_num_cpu_rate")
     self.activeUser = ""
     self.vio = VirtIoChannel(config.get("virtio", "device"))
     self.commandio = VirtIoChannel(config.get("commandio", "device"))
     #self.vio = VirtIoChannel("\\.\Global\com.redhat.rhevm.vdsm")
     #self.vio = VirtIoChannel("C:\\test")
     self.dr = None
     self.commandHandler = None
Example #3
0
 def __init__(self, config):
     logging.debug("AgentLogicBase:: __init__() entered")
     self.wait_stop = Event()
     self.heartBitRate = config.getint("general", "heart_beat_rate")
     self.userCheckRate = config.getint("general", "report_user_rate")
     self.appRefreshRate = config.getint("general", "report_application_rate")
     self.disksRefreshRate = config.getint("general", "report_disk_usage")
     self.activeUser = ""
     self.vio = VirtIoChannel(config.get("virtio", "device"))
     self.dr = None
     self.commandHandler = None
class AgentLogicBase:

    def __init__(self, config):
        logging.debug("AgentLogicBase:: __init__() entered")
        self.wait_stop = Event()
        self.heartBitRate = config.getint("general", "heart_beat_rate")
        self.userCheckRate = config.getint("general", "report_user_rate")
        self.appRefreshRate = config.getint("general",
                                            "report_application_rate")
        self.disksRefreshRate = config.getint("general", "report_disk_usage")
        self.numCPUsCheckRate = config.getint("general", "report_num_cpu_rate")
        self.activeUser = ""
        self.vio = VirtIoChannel(config.get("virtio", "device"))
        self.dr = None
        self.commandHandler = None

    def _send(self, name, arguments=None):
        version = _MESSAGE_MIN_API_VERSION.get(name, None)
        if version is None:
            logging.error('Undocumented message "%s"', name)
        elif version <= self.dr.getAPIVersion():
            logging.debug("Sending %s with args %s" % (name, arguments))
            self.vio.write(name, arguments or {})
        else:
            logging.debug("Message %s not supported by api version %d.",
                          name, self.dr.getAPIVersion())

    def run(self):
        logging.debug("AgentLogicBase:: run() entered")
        thread.start_new_thread(self.doListen, ())
        thread.start_new_thread(self.doWork, ())

        # Yuck! It's seem that Python block all signals when executing
        # a "real" code. So there is no way just to sit and wait (with
        # no timeout).
        # Try breaking out from this code snippet:
        # $ python -c "import threading; threading.Event().wait()"
        while not self.wait_stop.isSet():
            self.wait_stop.wait(1)

    def stop(self):
        logging.debug("AgentLogicBase:: baseStop() entered")
        self.wait_stop.set()

    def doWork(self):
        logging.debug("AgentLogicBase:: doWork() entered")
        self.sendInfo()
        self.sendUserInfo()
        self.sendAppList()
        self.sendFQDN()
        self.sendTimezone()
        self.sendOsInfo()
        counter = 0
        hbsecs = self.heartBitRate
        appsecs = self.appRefreshRate
        disksecs = self.disksRefreshRate
        usersecs = self.userCheckRate
        numcpusecs = self.numCPUsCheckRate
        reportedVersion = _DISABLED_API_VALUE

        try:
            while not self.wait_stop.isSet():
                counter += 1
                hbsecs -= 1
                if hbsecs <= 0:
                    self._send('heartbeat',
                               {'free-ram': self.dr.getAvailableRAM(),
                                'memory-stat': self.dr.getMemoryStats(),
                                'apiVersion': reportedVersion})
                    reportedVersion = _MAX_SUPPORTED_API_VERSION
                    hbsecs = self.heartBitRate
                usersecs -= 1
                if usersecs <= 0:
                    self.sendUserInfo()
                    usersecs = self.userCheckRate
                appsecs -= 1
                if appsecs <= 0:
                    self.sendAppList()
                    self.sendInfo()
                    self.sendFQDN()
                    appsecs = self.appRefreshRate
                disksecs -= 1
                if disksecs <= 0:
                    self.sendDisksUsages()
                    disksecs = self.disksRefreshRate
                numcpusecs -= 1
                if numcpusecs <= 0:
                    self.sendNumberOfCPUs()
                    numcpusecs = self.numCPUsCheckRate
                time.sleep(1)
            logging.debug("AgentLogicBase:: doWork() exiting")
        except:
            logging.exception("AgentLogicBase::doWork")

    def doListen(self):
        logging.debug("AgentLogicBase::doListen() - entered")
        if self.commandHandler is None:
            logging.debug("AgentLogicBase::doListen() - no commandHandler "
                          "... exiting doListen thread")
            return
        while not self.wait_stop.isSet():
            try:
                logging.debug("AgentLogicBase::doListen() - "
                              "in loop before vio.read")
                cmd, args = self.vio.read()
                if cmd:
                    self.parseCommand(cmd, args)
            except:
                logging.exception('Error while reading the virtio-serial '
                                  'channel.')
        logging.debug("AgentLogicBase::doListen() - exiting")

    def _onApiVersion(self, args):
        before = self.dr.apiVersion
        self.dr.setAPIVersion(args['apiVersion'])
        if before != self.dr.apiVersion:
            self._refresh()

    def _refresh(self):
        self.sendUserInfo(True)
        self.sendAppList()
        self.sendInfo()
        self.sendDisksUsages()
        self.sendFQDN()
        self.sendTimezone()
        self.sendOsInfo()

    def parseCommand(self, command, args):
        logging.info("Received an external command: %s..." % (command))
        if command == 'lock-screen':
            self.commandHandler.lock_screen()
        elif command == 'log-off':
            self.commandHandler.logoff()
        elif command == 'api-version':
            self._onApiVersion(args)
        elif command == 'shutdown':
            try:
                timeout = int(args['timeout'])
            except:
                timeout = 0
            try:
                msg = args['message']
            except:
                msg = 'System is going down'
            try:
                reboot = args['reboot'].lower() == 'true'
            except:
                reboot = False

            action = 'Shutting down'
            if reboot:
                action = 'Rebooting'
            logging.info("%s (timeout = %d, message = '%s')"
                         % (action, timeout, msg))
            self.commandHandler.shutdown(timeout, msg, reboot)
        elif command == 'login':
            username = args['username'].encode('utf8')
            password = args['password'].encode('utf8')
            credentials = struct.pack(
                '>I%ds%ds' % (len(username), len(password) + 1),
                len(username), username, password)
            logging.debug("User log-in (credentials = %s)"
                          % (safe_creds_repr(credentials)))
            self.commandHandler.login(credentials)
        elif command == 'refresh':
            if 'apiVersion' not in args and self.dr.getAPIVersion() > 0:
                logging.info('API versioning not supported by VDSM. Disabling '
                             'versioning support.')
                self.dr.setAPIVersion(_DISABLED_API_VALUE)
            self._refresh()
        elif command == 'echo':
            logging.debug("Echo: %s", args)
            self._send('echo', args)
        elif command == 'hibernate':
            state = args.get('state', 'disk')
            self.commandHandler.hibernate(state)
        elif command == 'set-number-of-cpus':
            count = args.get('count', 0)
            if count > 0:
                self.commandHandler.set_number_of_cpus(count)
                self.sendNumberOfCPUs()
        else:
            logging.error("Unknown external command: %s (%s)"
                          % (command, args))

    def sendFQDN(self):
        self._send('fqdn', {'fqdn': self.dr.getFQDN()})

    def sendUserInfo(self, force=False):
        cur_user = self.dr.getActiveUser()
        logging.debug("AgentLogicBase::sendUserInfo - cur_user = '******'" %
                      (cur_user))
        if cur_user != self.activeUser or force:
            self._send('active-user', {'name': cur_user})
            self.activeUser = cur_user

    def sendTimezone(self):
        ti = self.dr.getTimezoneInfo()
        self._send('timezone', {'zone': ti[0], 'offset': ti[1]})

    def sendInfo(self):
        self._send('host-name', {'name': self.dr.getMachineName()})
        self._send('os-version', {'version': self.dr.getOsVersion()})
        self._send('network-interfaces',
                   {'interfaces': self.dr.getAllNetworkInterfaces()})

    def sendAppList(self):
        self._send('applications', {'applications': self.dr.getApplications()})

    def sendDisksUsages(self):
        self._send('disks-usage', {'disks': self.dr.getDisksUsage(),
                                   'mapping': self.dr.getDiskMapping()})

    def sendMemoryStats(self):
        self._send('memory-stats', {'memory': self.dr.getMemoryStats()})

    def sendNumberOfCPUs(self):
        self._send('number-of-cpus', {'count': self.dr.getNumberOfCPUs()})

    def sendOsInfo(self):
        self._send('os-info', self.dr.getOsInfo())

    def sessionLogon(self):
        logging.debug("AgentLogicBase::sessionLogon: user logs on the system.")
        cur_user = self.dr.getActiveUser()
        retries = 0
        while (cur_user == 'None') and (retries < 5):
            time.sleep(1)
            cur_user = self.dr.getActiveUser()
            retries = retries + 1
        self.sendUserInfo()
        self._send('session-logon')

    def sessionLogoff(self):
        logging.debug("AgentLogicBase::sessionLogoff: "
                      "user logs off from the system.")
        self.activeUser = '******'
        self._send('session-logoff')
        self._send('active-user', {'name': self.activeUser})

    def sessionLock(self):
        logging.debug("AgentLogicBase::sessionLock: "
                      "user locks the workstation.")
        self._send('session-lock')

    def sessionUnlock(self):
        logging.debug("AgentLogicBase::sessionUnlock: "
                      "user unlocks the workstation.")
        self._send('session-unlock')

    def sessionStartup(self):
        logging.debug("AgentLogicBase::sessionStartup: system starts up.")
        self._send('session-startup')

    def sessionShutdown(self):
        logging.debug("AgentLogicBase::sessionShutdown: system shuts down.")
        self._send('session-shutdown')
Example #5
0
class AgentLogicBase:

    def __init__(self, config):
        logging.debug("AgentLogicBase:: __init__() entered")
        self.wait_stop = Event()
        self.heartBitRate = config.getint("general", "heart_beat_rate")
        self.userCheckRate = config.getint("general", "report_user_rate")
        self.appRefreshRate = config.getint("general",
                                            "report_application_rate")
        self.disksRefreshRate = config.getint("general", "report_disk_usage")
        self.numCPUsCheckRate = config.getint("general", "report_num_cpu_rate")
        self.activeUser = ""
        self.vio = VirtIoChannel(config.get("virtio", "device"))
        self.commandio = VirtIoChannel(config.get("commandio", "device"))
        #self.vio = VirtIoChannel("\\.\Global\com.redhat.rhevm.vdsm")
        #self.vio = VirtIoChannel("C:\\test")
        self.dr = None
        self.commandHandler = None

    def _send_command(self, name, arguments=None):
        version = _MESSAGE_MIN_API_VERSION.get(name, None)
        if version is None:
            logging.error('Undocumented message "%s"', name)
        elif version <= self.dr.getAPIVersion():
            logging.info("Sending %s with args %s" % (name, arguments))
            self.commandio.write(name, arguments or {})
        else:
            logging.info("Message %s not supported by api version %d.",
                          name, self.dr.getAPIVersion())

    def _send(self, name, arguments=None):
        version = _MESSAGE_MIN_API_VERSION.get(name, None)
        if version is None:
            logging.error('Undocumented message "%s"', name)
        elif version <= self.dr.getAPIVersion():
            logging.info("Sending %s with args %s" % (name, arguments))
            self.vio.write(name, arguments or {})
        else:
            logging.info("Message %s not supported by api version %d.",
                          name, self.dr.getAPIVersion())

    def run(self):
        logging.info("AgentLogicBase:: run() entered")
        thread.start_new_thread(self.doListen, ())
        thread.start_new_thread(self.doWork, ())

        # Yuck! It's seem that Python block all signals when executing
        # a "real" code. So there is no way just to sit and wait (with
        # no timeout).
        # Try breaking out from this code snippet:
        # $ python -c "import threading; threading.Event().wait()"
        while not self.wait_stop.isSet():
            self.wait_stop.wait(1)

    def stop(self):
        logging.debug("AgentLogicBase:: baseStop() entered")
        self.wait_stop.set()

    def doWork(self):
        logging.debug("AgentLogicBase:: doWork() entered")
        self.sendInfo()
        self.sendUserInfo()
        self.sendAppList()
        self.sendFQDN()
        counter = 0
        hbsecs = self.heartBitRate
        appsecs = self.appRefreshRate
        disksecs = self.disksRefreshRate
        usersecs = self.userCheckRate
        numcpusecs = self.numCPUsCheckRate

        try:
            while not self.wait_stop.isSet():
                counter += 1
                hbsecs -= 1
                if hbsecs <= 0:
                    self._send('heartbeat',
                               {'free-ram': self.dr.getAvailableRAM(),
                                'memory-stat': self.dr.getMemoryStats(),
                                'apiVersion': _MAX_SUPPORTED_API_VERSION})
                    hbsecs = self.heartBitRate
                usersecs -= 1
                if usersecs <= 0:
                    self.sendUserInfo()
                    usersecs = self.userCheckRate
                appsecs -= 1
                if appsecs <= 0:
                    self.sendAppList()
                    self.sendInfo()
                    self.sendFQDN()
                    appsecs = self.appRefreshRate
                disksecs -= 1
                if disksecs <= 0:
                    self.sendDisksUsages()
                    disksecs = self.disksRefreshRate
                numcpusecs -= 1
                if numcpusecs <= 0:
                    self.sendNumberOfCPUs()
                    numcpusecs = self.numCPUsCheckRate
                time.sleep(1)
            logging.debug("AgentLogicBase:: doWork() exiting")
        except:
            logging.exception("AgentLogicBase::doWork")

    def doListen(self):
        logging.debug("AgentLogicBase::doListen() - entered")
        if self.commandHandler is None:
            logging.debug("AgentLogicBase::doListen() - no commandHandler "
                          "... exiting doListen thread")
            return
        while not self.wait_stop.isSet():
            try:
                logging.debug("AgentLogicBase::doListen() - "
                              "in loop before vio.read")
                cmd, args = self.commandio.read()
                if cmd:
                    self.parseCommand(cmd, args)
            except:
                logging.exception('Error while reading the virtio-serial '
                                  'channel.')
        logging.debug("AgentLogicBase::doListen() - exiting")

    def _onApiVersion(self, args):
        self.dr.setAPIVersion(args['apiVersion'])

    def parseCommand(self, command, args):
        logging.info("Received an external command: %s..." % (command))
        if command == 'lock-screen':
            self.commandHandler.lock_screen()
        elif command == 'set_admin_password':
            try:
                password = args['admin_password']
            except:
                logging.error("empty password. password not set")
            ret = self.commandHandler.set_admin_password(password)
            logging.info("send set_admin_password result %d to host", ret)
            self._send_command('set_admin_password_result',{'ret': ret})
        elif command == 'rename':
            try:
                hostname = args['hostname']
            except:
                logging.error("empty hostname. hostname not set")
            ret = self.commandHandler.rename(hostname)
            logging.info("send rename result %d to host", ret)
            self._send_command('rename_result',{'ret': ret})
        elif command == 'log-off':
            self.commandHandler.logoff()
        elif command == 'api-version':
            self._onApiVersion(args)
        elif command == 'shutdown':
            try:
                timeout = int(args['timeout'])
            except:
                timeout = 0
            try:
                msg = args['message']
            except:
                msg = 'System is going down'
            try:
                reboot = args['reboot'].lower() == 'true'
            except:
                reboot = False

            action = 'Shutting down'
            if reboot:
                action = 'Rebooting'
            logging.info("%s (timeout = %d, message = '%s')"
                         % (action, timeout, msg))
            self.commandHandler.shutdown(timeout, msg, reboot)
        elif command == 'login':
            username = args['username'].encode('utf8')
            password = args['password'].encode('utf8')
            credentials = struct.pack(
                '>I%ds%ds' % (len(username), len(password) + 1),
                len(username), username, password)
            logging.debug("User log-in (credentials = %s)"
                          % (safe_creds_repr(credentials)))
            self.commandHandler.login(credentials)
        elif command == 'refresh':
            if 'apiVersion' not in args and self.dr.getAPIVersion() > 0:
                logging.info('API versioning not supported by VDSM. Disabling '
                             'versioning support.')
                self.dr.setAPIVersion(_DISABLED_API_VALUE)
            self.sendUserInfo(True)
            self.sendAppList()
            self.sendInfo()
            self.sendDisksUsages()
            self.sendFQDN()
        elif command == 'echo':
            logging.debug("Echo: %s", args)
            self._send('echo', args)
        elif command == 'hibernate':
            state = args.get('state', 'disk')
            self.commandHandler.hibernate(state)
        elif command == 'set-number-of-cpus':
            count = args.get('count', 0)
            if count > 0:
                self.commandHandler.set_number_of_cpus(count)
                self.sendNumberOfCPUs()
        else:
            logging.error("Unknown external command: %s (%s)"
                          % (command, args))

    def sendFQDN(self):
        self._send('fqdn', {'fqdn': self.dr.getFQDN()})

    def sendUserInfo(self, force=False):
        cur_user = self.dr.getActiveUser()
        logging.debug("AgentLogicBase::sendUserInfo - cur_user = '******'" %
                      (cur_user))
        if cur_user != self.activeUser or force:
            self._send('active-user', {'name': cur_user})
            self.activeUser = cur_user

    def sendInfo(self):
        self._send('host-name', {'name': self.dr.getMachineName()})
        self._send('os-version', {'version': self.dr.getOsVersion()})
        self._send('network-interfaces',
                   {'interfaces': self.dr.getAllNetworkInterfaces()})

    def sendAppList(self):
        self._send('applications', {'applications': self.dr.getApplications()})

    def sendDisksUsages(self):
        self._send('disks-usage', {'disks': self.dr.getDisksUsage(),
                                   'mapping': self.dr.getDiskMapping()})

    def sendMemoryStats(self):
        self._send('memory-stats', {'memory': self.dr.getMemoryStats()})

    def sendNumberOfCPUs(self):
        self._send('number-of-cpus', {'count': self.dr.getNumberOfCPUs()})

    def sessionLogon(self):
        logging.debug("AgentLogicBase::sessionLogon: user logs on the system.")
        cur_user = self.dr.getActiveUser()
        retries = 0
        while (cur_user == 'None') and (retries < 5):
            time.sleep(1)
            cur_user = self.dr.getActiveUser()
            retries = retries + 1
        self.sendUserInfo()
        self._send('session-logon')

    def sessionLogoff(self):
        logging.debug("AgentLogicBase::sessionLogoff: "
                      "user logs off from the system.")
        self.activeUser = '******'
        self._send('session-logoff')
        self._send('active-user', {'name': self.activeUser})

    def sessionLock(self):
        logging.debug("AgentLogicBase::sessionLock: "
                      "user locks the workstation.")
        self._send('session-lock')

    def sessionUnlock(self):
        logging.debug("AgentLogicBase::sessionUnlock: "
                      "user unlocks the workstation.")
        self._send('session-unlock')

    def sessionStartup(self):
        logging.debug("AgentLogicBase::sessionStartup: system starts up.")
        self._send('session-startup')

    def sessionShutdown(self):
        logging.debug("AgentLogicBase::sessionShutdown: system shuts down.")
        self._send('session-shutdown')
class AgentLogicBase:

    def __init__(self, config):
        logging.debug("AgentLogicBase:: __init__() entered")
        self.wait_stop = Event()
        self.heartBitRate = config.getint("general", "heart_beat_rate")
        self.userCheckRate = config.getint("general", "report_user_rate")
        self.appRefreshRate = config.getint("general",
                                            "report_application_rate")
        self.disksRefreshRate = config.getint("general", "report_disk_usage")
        self.activeUser = ""
        self.vio = VirtIoChannel(config.get("virtio", "device"))
        self.dr = None
        self.commandHandler = None

    def run(self):
        logging.debug("AgentLogicBase:: run() entered")
        thread.start_new_thread(self.doListen, ())
        thread.start_new_thread(self.doWork, ())

        # Yuck! It's seem that Python block all signals when executing
        # a "real" code. So there is no way just to sit and wait (with
        # no timeout).
        # Try breaking out from this code snippet:
        # $ python -c "import threading; threading.Event().wait()"
        while not self.wait_stop.isSet():
            self.wait_stop.wait(1)

    def stop(self):
        logging.debug("AgentLogicBase:: baseStop() entered")
        self.wait_stop.set()

    def doWork(self):
        logging.debug("AgentLogicBase:: doWork() entered")
        self.sendInfo()
        self.sendUserInfo()
        self.sendAppList()
        counter = 0
        hbsecs = self.heartBitRate
        appsecs = self.appRefreshRate
        disksecs = self.disksRefreshRate
        usersecs = self.userCheckRate

        try:
            while not self.wait_stop.isSet():
                counter += 1
                hbsecs -= 1
                if hbsecs <= 0:
                    self.vio.write('heartbeat',
                                   {'free-ram': self.dr.getAvailableRAM(),
                                    'memory-stat': self.dr.getMemoryStats()})
                    hbsecs = self.heartBitRate
                usersecs -= 1
                if usersecs <= 0:
                    self.sendUserInfo()
                    usersecs = self.userCheckRate
                appsecs -= 1
                if appsecs <= 0:
                    self.sendAppList()
                    self.sendInfo()
                    appsecs = self.appRefreshRate
                disksecs -= 1
                if disksecs <= 0:
                    self.sendDisksUsages()
                    disksecs = self.disksRefreshRate
                time.sleep(1)
            logging.debug("AgentLogicBase:: doWork() exiting")
        except:
            logging.exception("AgentLogicBase::doWork")

    def doListen(self):
        logging.debug("AgentLogicBase::doListen() - entered")
        if self.commandHandler is None:
            logging.debug("AgentLogicBase::doListen() - no commandHandler "
                          "... exiting doListen thread")
            return
        while not self.wait_stop.isSet():
            try:
                logging.debug("AgentLogicBase::doListen() - "
                              "in loop before vio.read")
                cmd, args = self.vio.read()
                if cmd:
                    self.parseCommand(cmd, args)
            except:
                logging.exception('Error while reading the virtio-serial '
                                  'channel.')
        logging.debug("AgentLogicBase::doListen() - exiting")

    def parseCommand(self, command, args):
        logging.info("Received an external command: %s..." % (command))
        if command == 'lock-screen':
            self.commandHandler.lock_screen()
        elif command == 'log-off':
            self.commandHandler.logoff()
        elif command == 'shutdown':
            try:
                timeout = int(args['timeout'])
            except:
                timeout = 0
            try:
                msg = args['message']
            except:
                msg = 'System is going down'
            logging.info("Shutting down (timeout = %d, message = '%s')"
                         % (timeout, msg))
            self.commandHandler.shutdown(timeout, msg)
        elif command == 'login':
            username = args['username'].encode('utf8')
            password = args['password'].encode('utf8')
            credentials = struct.pack(
                '>I%ds%ds' % (len(username), len(password) + 1),
                len(username), username, password)
            logging.debug("User log-in (credentials = %s)"
                          % (safe_creds_repr(credentials)))
            self.commandHandler.login(credentials)
        elif command == 'refresh':
            self.sendUserInfo(True)
            self.sendAppList()
            self.sendInfo()
            self.sendDisksUsages()
        elif command == 'echo':
            logging.debug("Echo: %s", args)
            self.vio.write('echo', args)
        elif command == 'hibernate':
            state = args.get('state', 'disk')
            self.commandHandler.hibernate(state)
        else:
            logging.error("Unknown external command: %s (%s)"
                          % (command, args))

    def sendUserInfo(self, force=False):
        cur_user = str(self.dr.getActiveUser())
        logging.debug("AgentLogicBase::sendUserInfo - cur_user = '******'" %
                      (cur_user))
        if cur_user != self.activeUser or force:
            self.vio.write('active-user', {'name': cur_user})
            self.activeUser = cur_user

    def sendInfo(self):
        self.vio.write('host-name', {'name': self.dr.getMachineName()})
        self.vio.write('os-version', {'version': self.dr.getOsVersion()})
        self.vio.write('network-interfaces',
                       {'interfaces': self.dr.getAllNetworkInterfaces()})

    def sendAppList(self):
        self.vio.write('applications',
                       {'applications': self.dr.getApplications()})

    def sendDisksUsages(self):
        self.vio.write('disks-usage', {'disks': self.dr.getDisksUsage()})

    def sendMemoryStats(self):
        self.vio.write('memory-stats', {'memory': self.dr.getMemoryStats()})

    def sessionLogon(self):
        logging.debug("AgentLogicBase::sessionLogon: user logs on the system.")
        cur_user = self.dr.getActiveUser()
        retries = 0
        while (cur_user == 'None') and (retries < 5):
            time.sleep(1)
            cur_user = self.dr.getActiveUser()
            retries = retries + 1
        self.sendUserInfo()
        self.vio.write('session-logon')

    def sessionLogoff(self):
        logging.debug("AgentLogicBase::sessionLogoff: "
                      "user logs off from the system.")
        self.activeUser = '******'
        self.vio.write('session-logoff')
        self.vio.write('active-user', {'name': self.activeUser})

    def sessionLock(self):
        logging.debug("AgentLogicBase::sessionLock: "
                      "user locks the workstation.")
        self.vio.write('session-lock')

    def sessionUnlock(self):
        logging.debug("AgentLogicBase::sessionUnlock: "
                      "user unlocks the workstation.")
        self.vio.write('session-unlock')

    def sessionStartup(self):
        logging.debug("AgentLogicBase::sessionStartup: system starts up.")
        self.vio.write('session-startup')

    def sessionShutdown(self):
        logging.debug("AgentLogicBase::sessionShutdown: system shuts down.")
        self.vio.write('session-shutdown')
Example #7
0
class AgentLogicBase:
    def __init__(self, config):
        logging.debug("AgentLogicBase:: __init__() entered")
        self.wait_stop = Event()
        self.heartBitRate = config.getint("general", "heart_beat_rate")
        self.userCheckRate = config.getint("general", "report_user_rate")
        self.appRefreshRate = config.getint("general", "report_application_rate")
        self.disksRefreshRate = config.getint("general", "report_disk_usage")
        self.activeUser = ""
        self.vio = VirtIoChannel(config.get("virtio", "device"))
        self.dr = None
        self.commandHandler = None

    def run(self):
        logging.debug("AgentLogicBase:: run() entered")
        thread.start_new_thread(self.doListen, ())
        thread.start_new_thread(self.doWork, ())

        # Yuck! It's seem that Python block all signals when executing
        # a "real" code. So there is no way just to sit and wait (with
        # no timeout).
        # Try breaking out from this code snippet:
        # $ python -c "import threading; threading.Event().wait()"
        while not self.wait_stop.isSet():
            self.wait_stop.wait(1)

    def stop(self):
        logging.debug("AgentLogicBase:: baseStop() entered")
        self.wait_stop.set()

    def doWork(self):
        logging.debug("AgentLogicBase:: doWork() entered")
        self.sendInfo()
        self.sendUserInfo()
        self.sendAppList()
        counter = 0
        hbsecs = self.heartBitRate
        appsecs = self.appRefreshRate
        disksecs = self.disksRefreshRate
        usersecs = self.userCheckRate

        try:
            while not self.wait_stop.isSet():
                counter += 1
                hbsecs -= 1
                if hbsecs <= 0:
                    self.vio.write("heartbeat", {"free-ram": self.dr.getAvailableRAM()})
                    hbsecs = self.heartBitRate
                usersecs -= 1
                if usersecs <= 0:
                    self.sendUserInfo()
                    usersecs = self.userCheckRate
                appsecs -= 1
                if appsecs <= 0:
                    self.sendAppList()
                    self.sendInfo()
                    appsecs = self.appRefreshRate
                disksecs -= 1
                if disksecs <= 0:
                    self.sendDisksUsages()
                    disksecs = self.disksRefreshRate
                time.sleep(1)
            logging.debug("AgentLogicBase:: doWork() exiting")
        except:
            logging.exception("AgentLogicBase::doWork")

    def doListen(self):
        logging.debug("AgentLogicBase::doListen() - entered")
        if self.commandHandler == None:
            logging.debug("AgentLogicBase::doListen() - no commandHandler ... exiting doListen thread")
            return
        while not self.wait_stop.isSet():
            try:
                logging.debug("AgentLogicBase::doListen() - in loop before vio.read")
                cmd, args = self.vio.read()
                logging.debug("AgentLogicBase::doListen() - read something")
                logging.debug(cmd)
                logging.debug(args)
                if cmd:
                    self.parseCommand(cmd, args)
            except:
                logging.exception("Error while reading the virtio-serial channel.")
        logging.debug("AgentLogicBase::doListen() - exiting")

    def parseCommand(self, command, args):
        logging.info("Received an external command: %s..." % (command))
        if command == "lock-screen":
            self.commandHandler.lock_screen()
        elif command == "log-off":
            self.commandHandler.logoff()
        elif command == "shutdown":
            try:
                timeout = int(args["timeout"])
            except:
                timeout = 0
            try:
                msg = args["message"]
            except:
                msg = "System is going down"
            logging.info("Shutting down (timeout = %d, message = '%s')" % (timeout, msg))
            self.commandHandler.shutdown(timeout, msg)
        elif command == "login":
            username = args["username"].encode("utf8")
            password = args["password"].encode("utf8")
            credentials = struct.pack(
                ">I%ds%ds" % (len(username), len(password) + 1), len(username), username, password
            )
            logging.debug("User log-in (credentials = %s)" % (safe_creds_repr(credentials)))
            self.commandHandler.login(credentials)
        elif command == "refresh":
            self.sendUserInfo(True)
            self.sendAppList()
            self.sendInfo()
            self.sendDisksUsages()
        elif command == "echo":
            logging.debug("Echo: %s", args)
            self.vio.write("echo", args)
        elif command == "etasp":
            method = args["method"].encode("utf8")
            logging.debug("ETASP command: %s", method)
            res = self.commandHandler.etasp_read(method)
            if res != "":
                self.sendAppInfo("etasp", method, res, args)
        else:
            logging.error("Unknown external command: %s (%s)" % (command, args))

    def sendUserInfo(self, force=False):
        cur_user = str(self.dr.getActiveUser())
        logging.debug("AgentLogicBase::sendUserInfo - cur_user = '******'" % (cur_user))
        if cur_user != self.activeUser or force:
            self.vio.write("active-user", {"name": cur_user})
            self.activeUser = cur_user

    def sendInfo(self):
        self.vio.write("host-name", {"name": self.dr.getMachineName()})
        self.vio.write("os-version", {"version": self.dr.getOsVersion()})
        self.vio.write("network-interfaces", {"interfaces": self.dr.getAllNetworkInterfaces()})

    def sendAppList(self):
        self.vio.write("applications", {"applications": self.dr.getApplications()})

    def sendAppInfo(self, appname, method, msg, args):
        logging.debug(msg)
        obj = json.loads(msg.decode("utf8"))
        if method == "getInstanceMetadata":
            obj["msg"]["debug_mode"] = str(obj["msg"]["debug_mode"])
        logging.debug("message")
        logging.debug(obj)
        self.vio.write(appname, {method: obj["msg"], "id": args["id"]})

    def sendDisksUsages(self):
        self.vio.write("disks-usage", {"disks": self.dr.getDisksUsage()})

    def sessionLogon(self):
        logging.debug("AgentLogicBase::sessionLogon: user logs on the system.")
        cur_user = self.dr.getActiveUser()
        retries = 0
        while (cur_user == "None") and (retries < 5):
            time.sleep(1)
            cur_user = self.dr.getActiveUser()
            retries = retries + 1
        self.sendUserInfo()
        self.vio.write("session-logon")

    def sessionLogoff(self):
        logging.debug("AgentLogicBase::sessionLogoff: user logs off from the system.")
        self.activeUser = "******"
        self.vio.write("session-logoff")
        self.vio.write("active-user", {"name": self.activeUser})

    def sessionLock(self):
        logging.debug("AgentLogicBase::sessionLock: user locks the workstation.")
        self.vio.write("session-lock")

    def sessionUnlock(self):
        logging.debug("AgentLogicBase::sessionUnlock: user unlocks the workstation.")
        self.vio.write("session-unlock")

    def sessionStartup(self):
        logging.debug("AgentLogicBase::sessionStartup: system starts up.")
        self.vio.write("session-startup")

    def sessionShutdown(self):
        logging.debug("AgentLogicBase::sessionShutdown: system shuts down.")
        self.vio.write("session-shutdown")
class AgentLogicBase:
    def __init__(self, config):
        logging.debug("AgentLogicBase:: __init__() entered")
        self.wait_stop = Event()
        self.heartBitRate = config.getint("general", "heart_beat_rate")
        self.userCheckRate = config.getint("general", "report_user_rate")
        self.appRefreshRate = config.getint("general", "report_application_rate")
        self.disksRefreshRate = config.getint("general", "report_disk_usage")
        self.numCPUsCheckRate = config.getint("general", "report_num_cpu_rate")
        self.activeUser = ""
        self.vio = VirtIoChannel(config.get("virtio", "device"))
        self.dr = None
        self.commandHandler = None

    def _send(self, name, arguments=None):
        version = _MESSAGE_MIN_API_VERSION.get(name, None)
        if version is None:
            logging.error('Undocumented message "%s"', name)
        elif version <= self.dr.getAPIVersion():
            logging.debug("Sending %s with args %s" % (name, arguments))
            self.vio.write(name, arguments or {})
        else:
            logging.debug("Message %s not supported by api version %d.", name, self.dr.getAPIVersion())

    def run(self):
        logging.debug("AgentLogicBase:: run() entered")
        thread.start_new_thread(self.doListen, ())
        thread.start_new_thread(self.doWork, ())

        # Yuck! It's seem that Python block all signals when executing
        # a "real" code. So there is no way just to sit and wait (with
        # no timeout).
        # Try breaking out from this code snippet:
        # $ python -c "import threading; threading.Event().wait()"
        while not self.wait_stop.isSet():
            self.wait_stop.wait(1)

    def stop(self):
        logging.debug("AgentLogicBase:: baseStop() entered")
        self.wait_stop.set()

    def doWork(self):
        logging.debug("AgentLogicBase:: doWork() entered")
        self.sendInfo()
        self.sendUserInfo()
        self.sendAppList()
        self.sendFQDN()
        counter = 0
        hbsecs = self.heartBitRate
        appsecs = self.appRefreshRate
        disksecs = self.disksRefreshRate
        usersecs = self.userCheckRate
        numcpusecs = self.numCPUsCheckRate

        try:
            while not self.wait_stop.isSet():
                counter += 1
                hbsecs -= 1
                if hbsecs <= 0:
                    self._send(
                        "heartbeat",
                        {
                            "free-ram": self.dr.getAvailableRAM(),
                            "memory-stat": self.dr.getMemoryStats(),
                            "apiVersion": _MAX_SUPPORTED_API_VERSION,
                        },
                    )
                    hbsecs = self.heartBitRate
                usersecs -= 1
                if usersecs <= 0:
                    self.sendUserInfo()
                    usersecs = self.userCheckRate
                appsecs -= 1
                if appsecs <= 0:
                    self.sendAppList()
                    self.sendInfo()
                    self.sendFQDN()
                    appsecs = self.appRefreshRate
                disksecs -= 1
                if disksecs <= 0:
                    self.sendDisksUsages()
                    disksecs = self.disksRefreshRate
                numcpusecs -= 1
                if numcpusecs <= 0:
                    self.sendNumberOfCPUs()
                    numcpusecs = self.numCPUsCheckRate
                time.sleep(1)
            logging.debug("AgentLogicBase:: doWork() exiting")
        except:
            logging.exception("AgentLogicBase::doWork")

    def doListen(self):
        logging.debug("AgentLogicBase::doListen() - entered")
        if self.commandHandler is None:
            logging.debug("AgentLogicBase::doListen() - no commandHandler " "... exiting doListen thread")
            return
        while not self.wait_stop.isSet():
            try:
                logging.debug("AgentLogicBase::doListen() - " "in loop before vio.read")
                cmd, args = self.vio.read()
                if cmd:
                    self.parseCommand(cmd, args)
            except:
                logging.exception("Error while reading the virtio-serial " "channel.")
        logging.debug("AgentLogicBase::doListen() - exiting")

    def _onApiVersion(self, args):
        self.dr.setAPIVersion(args["apiVersion"])

    def parseCommand(self, command, args):
        logging.info("Received an external command: %s..." % (command))
        if command == "lock-screen":
            self.commandHandler.lock_screen()
        elif command == "log-off":
            self.commandHandler.logoff()
        elif command == "api-version":
            self._onApiVersion(args)
        elif command == "shutdown":
            try:
                timeout = int(args["timeout"])
            except:
                timeout = 0
            try:
                msg = args["message"]
            except:
                msg = "System is going down"
            try:
                reboot = args["reboot"].lower() == "true"
            except:
                reboot = False

            action = "Shutting down"
            if reboot:
                action = "Rebooting"
            logging.info("%s (timeout = %d, message = '%s')" % (action, timeout, msg))
            self.commandHandler.shutdown(timeout, msg, reboot)
        elif command == "login":
            username = args["username"].encode("utf8")
            password = args["password"].encode("utf8")
            credentials = struct.pack(
                ">I%ds%ds" % (len(username), len(password) + 1), len(username), username, password
            )
            logging.debug("User log-in (credentials = %s)" % (safe_creds_repr(credentials)))
            self.commandHandler.login(credentials)
        elif command == "refresh":
            if "apiVersion" not in args and self.dr.getAPIVersion() > 0:
                logging.info("API versioning not supported by VDSM. Disabling " "versioning support.")
                self.dr.setAPIVersion(_DISABLED_API_VALUE)
            self.sendUserInfo(True)
            self.sendAppList()
            self.sendInfo()
            self.sendDisksUsages()
            self.sendFQDN()
        elif command == "echo":
            logging.debug("Echo: %s", args)
            self._send("echo", args)
        elif command == "hibernate":
            state = args.get("state", "disk")
            self.commandHandler.hibernate(state)
        elif command == "set-number-of-cpus":
            count = args.get("count", 0)
            if count > 0:
                self.commandHandler.set_number_of_cpus(count)
                self.sendNumberOfCPUs()
        else:
            logging.error("Unknown external command: %s (%s)" % (command, args))

    def sendFQDN(self):
        self._send("fqdn", {"fqdn": self.dr.getFQDN()})

    def sendUserInfo(self, force=False):
        cur_user = self.dr.getActiveUser()
        logging.debug("AgentLogicBase::sendUserInfo - cur_user = '******'" % (cur_user))
        if cur_user != self.activeUser or force:
            self._send("active-user", {"name": cur_user})
            self.activeUser = cur_user

    def sendInfo(self):
        self._send("host-name", {"name": self.dr.getMachineName()})
        self._send("os-version", {"version": self.dr.getOsVersion()})
        self._send("network-interfaces", {"interfaces": self.dr.getAllNetworkInterfaces()})

    def sendAppList(self):
        self._send("applications", {"applications": self.dr.getApplications()})

    def sendDisksUsages(self):
        self._send("disks-usage", {"disks": self.dr.getDisksUsage(), "mapping": self.dr.getDiskMapping()})

    def sendMemoryStats(self):
        self._send("memory-stats", {"memory": self.dr.getMemoryStats()})

    def sendNumberOfCPUs(self):
        self._send("number-of-cpus", {"count": self.dr.getNumberOfCPUs()})

    def sessionLogon(self):
        logging.debug("AgentLogicBase::sessionLogon: user logs on the system.")
        cur_user = self.dr.getActiveUser()
        retries = 0
        while (cur_user == "None") and (retries < 5):
            time.sleep(1)
            cur_user = self.dr.getActiveUser()
            retries = retries + 1
        self.sendUserInfo()
        self._send("session-logon")

    def sessionLogoff(self):
        logging.debug("AgentLogicBase::sessionLogoff: " "user logs off from the system.")
        self.activeUser = "******"
        self._send("session-logoff")
        self._send("active-user", {"name": self.activeUser})

    def sessionLock(self):
        logging.debug("AgentLogicBase::sessionLock: " "user locks the workstation.")
        self._send("session-lock")

    def sessionUnlock(self):
        logging.debug("AgentLogicBase::sessionUnlock: " "user unlocks the workstation.")
        self._send("session-unlock")

    def sessionStartup(self):
        logging.debug("AgentLogicBase::sessionStartup: system starts up.")
        self._send("session-startup")

    def sessionShutdown(self):
        logging.debug("AgentLogicBase::sessionShutdown: system shuts down.")
        self._send("session-shutdown")
class AgentLogicBase:

    def __init__(self, config):
        logging.debug("AgentLogicBase:: __init__() entered")
        self.wait_stop = Event()
        self.heartBitRate = config.getint("general", "heart_beat_rate")
        self.userCheckRate = config.getint("general", "report_user_rate")
        self.appRefreshRate = config.getint("general", "report_application_rate")
        self.disksRefreshRate = config.getint("general", "report_disk_usage")
        self.activeUser = ""
        self.vio = VirtIoChannel(config.get("virtio", "device"))
        self.dr = None
        self.commandHandler = None

    def run(self):
        logging.debug("AgentLogicBase:: run() entered")
        thread.start_new_thread(self.doListen, ())
        thread.start_new_thread(self.doWork, ())

        # Yuck! It's seem that Python block all signals when executing
        # a "real" code. So there is no way just to sit and wait (with
        # no timeout).
        # Try breaking out from this code snippet:
        # $ python -c "import threading; threading.Event().wait()"
        while not self.wait_stop.isSet():
            self.wait_stop.wait(1)

    def stop(self):
        logging.debug("AgentLogicBase:: baseStop() entered")
        self.wait_stop.set()

    def doWork(self):
        logging.debug("AgentLogicBase:: doWork() entered")
        self.sendInfo()
        self.sendUserInfo()
        self.sendAppList()
        counter = 0
        hbsecs = self.heartBitRate
        appsecs = self.appRefreshRate
        disksecs = self.disksRefreshRate
        usersecs = self.userCheckRate

        try:
            while not self.wait_stop.isSet():
                counter +=1
                hbsecs -= 1
                if hbsecs <= 0:
                    self.vio.write('heartbeat',
                                   {'free-ram' : self.dr.getAvailableRAM(),
                                    'memory-stat' : self.dr.getMemoryStats(),
                                    'totalrdpconnections' : self.dr.getTotalRDPConnections()})
                    hbsecs = self.heartBitRate
                usersecs -=1
                if usersecs <=0:
                    self.sendUserInfo()
                    usersecs = self.userCheckRate
                appsecs -= 1
                if appsecs <= 0:
                    self.sendAppList()
                    self.sendInfo()
                    appsecs = self.appRefreshRate
                disksecs -= 1
                if disksecs <= 0:
                    self.sendDisksUsages()
                    disksecs = self.disksRefreshRate
                time.sleep(1)
            logging.debug("AgentLogicBase:: doWork() exiting")
        except:
            logging.exception("AgentLogicBase::doWork")

    def doListen(self):
        logging.debug("AgentLogicBase::doListen() - entered")
        if self.commandHandler == None:
            logging.debug("AgentLogicBase::doListen() - no commandHandler ... exiting doListen thread")
            return
        while not self.wait_stop.isSet():
            try:
                logging.debug("AgentLogicBase::doListen() - in loop before vio.read")
                cmd, args = self.vio.read()
                if cmd:
                    self.parseCommand(cmd, args)
            except:
                logging.exception('Error while reading the virtio-serial channel.')
        logging.debug("AgentLogicBase::doListen() - exiting")

    def parseCommand(self, command, args):
        logging.info("Received an external command: %s..." % (command))
        if command == 'lock-screen':
            self.commandHandler.lock_screen()
        elif command == 'log-off':
            self.commandHandler.logoff()
        elif command == 'shutdown':
            try:
                timeout = int(args['timeout'])
            except:
                timeout = 0
            try:
                msg = args['message']
            except:
                msg = 'System is going down'
            logging.info("Shutting down (timeout = %d, message = '%s')" % (timeout, msg))
            self.commandHandler.shutdown(timeout, msg)
        elif command == 'login':
            username = args['username'].encode('utf8')
            password = args['password'].encode('utf8')
            credentials = struct.pack('>I%ds%ds' % (len(username), len(password) + 1),
                len(username), username, password)
            logging.debug("User log-in (credentials = %s)" % (safe_creds_repr(credentials)))
            self.commandHandler.login(credentials)
        elif command == 'refresh':
            self.sendUserInfo(True)
            self.sendAppList()
            self.sendInfo()
            self.sendDisksUsages()
        elif command == 'echo':
            logging.debug("Echo: %s", args)
            self.vio.write('echo', args)
        elif command == 'hibernate':
            state = args.get('state', 'disk')
            self.commandHandler.hibernate(state)
        elif command == 'reboot':
            self.commandHandler.reboot()
        else:
            logging.error("Unknown external command: %s (%s)" % (command, args))

    def sendUserInfo(self, force=False):
        cur_user = str(self.dr.getActiveUser())
        logging.debug("AgentLogicBase::sendUserInfo - cur_user = '******'"%(cur_user))
        if cur_user != self.activeUser or force:
            self.vio.write('active-user', { 'name' : cur_user })
            self.activeUser = cur_user

    def sendInfo(self):
        self.vio.write('host-name', { 'name' : self.dr.getMachineName() })
        self.vio.write('os-version', { 'version' : self.dr.getOsVersion() })
        self.vio.write('network-interfaces', { 'interfaces' : self.dr.getAllNetworkInterfaces() })

    def sendAppList(self):
        self.vio.write('applications', { 'applications' : self.dr.getApplications() })

    def sendDisksUsages(self):
        self.vio.write('disks-usage', { 'disks' : self.dr.getDisksUsage() })

    def sendMemoryStats(self):
        self.vio.write('memory-stats', { 'memory' : self.dr.getMemoryStats() })

    def sessionLogon(self):
        logging.debug("AgentLogicBase::sessionLogon: user logs on the system.")
        cur_user = self.dr.getActiveUser()
        retries = 0
        while (cur_user == 'None') and (retries < 5):
            time.sleep(1)
            cur_user = self.dr.getActiveUser()
            retries = retries + 1
        self.sendUserInfo()
        self.vio.write('session-logon')

    def sessionLogoff(self):
        logging.debug("AgentLogicBase::sessionLogoff: user logs off from the system.")
        self.activeUser = '******'
        self.vio.write('session-logoff')
        self.vio.write('active-user', { 'name' : self.activeUser })

    def sessionLock(self):
        logging.debug("AgentLogicBase::sessionLock: user locks the workstation.")
        self.vio.write('session-lock')

    def sessionUnlock(self):
        logging.debug("AgentLogicBase::sessionUnlock: user unlocks the workstation.")
        self.vio.write('session-unlock')

    def sessionStartup(self):
        logging.debug("AgentLogicBase::sessionStartup: system starts up.")
        self.vio.write('session-startup')

    def sessionShutdown(self):
        logging.debug("AgentLogicBase::sessionShutdown: system shuts down.")
        self.vio.write('session-shutdown')