コード例 #1
0
    def ask(self, username, display):

        result = self.db_service.select('contract', ['content', 'title', 'id'],
                                        'id =(select MAX(id) from contract)')

        if result is None or len(result) < 1:
            content = 'Ahenk kurulu bu bilgisayarda ilk defa oturum açıyorsunuz. ' \
                      'Devam ederseniz Lider-Ahenk in bilgisayar üzeride yapacağı ' \
                      'tüm işlemlere onay vermiş sayılacaksınız. Kabul ediyor musunuz?' \
                      ' \n(Tanımlanmış zaman aralığında olumlu cevaplandırmadığınız takdirde oturumunuz ' \
                      'sonlandırılacaktır.)'
            title = 'Ahenk Kurulu Bilgisayar Kullanım Anlaşması'
            contract_id = '-1'
        else:
            content = str(result[0][0])
            title = result[0][1]
            contract_id = result[0][2]
        try:
            agreement_path = System.Ahenk.received_dir_path(
            ) + Util.generate_uuid()
            Util.write_file(agreement_path, content)
            Util.set_permission(agreement_path, 777)
            command = 'export DISPLAY={0};su - {1} -c \'python3 {2} \"$(cat {3})\" \"{4}\"\''.format(
                display, username, self.ask_path, agreement_path, title)
            result_code, p_out, p_err = Util.execute(command)

            pout = str(p_out).replace('\n', '')
            if pout != 'Error':
                if pout == 'Y':
                    self.logger.debug(
                        'Agreement was accepted by {0}.'.format(username))
                    self.db_service.update(
                        'agreement', self.db_service.get_cols('agreement'),
                        [contract_id, username,
                         Util.timestamp(), 'Y'])
                elif pout == 'N':
                    self.db_service.update(
                        'agreement', self.db_service.get_cols('agreement'),
                        [contract_id, username,
                         Util.timestamp(), 'N'])
                    self.logger.debug(
                        'Agreement was ignored by {0}. Session will be closed'.
                        format(username))
                else:
                    self.logger.error(
                        'A problem occurred while executing ask.py. Error Message: {0}'
                        .format(str(pout)))
                Util.delete_file(agreement_path)
            else:
                self.logger.error(
                    'A problem occurred while executing ask.py (Probably argument fault). Error Message: {0}'
                    .format(str(pout)))

        except Exception as e:
            self.logger.error(
                'A Problem occurred while displaying agreement. Error Message: {0}'
                .format(str(e)))
コード例 #2
0
ファイル: agreement.py プロジェクト: Pardus-Kurumsal/ahenk
    def ask(self, username, display):

        result = self.db_service.select('contract', ['content', 'title', 'id'], 'id =(select MAX(id) from contract)')

        if result is None or len(result) < 1:
            content = 'Ahenk kurulu bu bilgisayarda ilk defa oturum açıyorsunuz. ' \
                      'Devam ederseniz Lider-Ahenk in bilgisayar üzeride yapacağı ' \
                      'tüm işlemlere onay vermiş sayılacaksınız. Kabul ediyor musunuz?' \
                      ' \n(Tanımlanmış zaman aralığında olumlu cevaplandırmadığınız takdirde oturumunuz ' \
                      'sonlandırılacaktır.)'
            title = 'Ahenk Kurulu Bilgisayar Kullanım Anlaşması'
            contract_id = '-1'
        else:
            content = str(result[0][0])
            title = result[0][1]
            contract_id = result[0][2]
        try:
            agreement_path = System.Ahenk.received_dir_path() + Util.generate_uuid()
            Util.write_file(agreement_path, content)
            Util.set_permission(agreement_path, 777)
            command = 'export DISPLAY={0};su - {1} -c \'python3 {2} \"$(cat {3})\" \"{4}\"\''.format(display, username,
                                                                                                     self.ask_path,
                                                                                                     agreement_path,
                                                                                                     title)
            result_code, p_out, p_err = Util.execute(command)
            pout = str(p_out).replace('\n', '')
            if pout != 'Error':
                if pout == 'Y':
                    self.logger.debug('Agreement was accepted by {0}.'.format(username))
                    self.db_service.update('agreement', self.db_service.get_cols('agreement'),
                                           [contract_id, username, Util.timestamp(), 'Y'])
                elif pout == 'N':
                    self.db_service.update('agreement', self.db_service.get_cols('agreement'),
                                           [contract_id, username, Util.timestamp(), 'N'])
                    self.logger.debug(
                        'Agreement was ignored by {0}. Session will be closed'.format(username))
                else:
                    self.logger.error(
                        'A problem occurred while executing ask.py. Error Message: {0}'.format(str(pout)))
                Util.delete_file(agreement_path)
            else:
                self.logger.error(
                    'A problem occurred while executing ask.py (Probably argument fault). Error Message: {0}'.format(
                        str(pout)))

        except Exception as e:
            self.logger.error(
                'A Problem occurred while displaying agreement. Error Message: {0}'.format(str(e)))
コード例 #3
0
ファイル: messaging.py プロジェクト: hasankara/windows-agent
    def unregister_msg(self):

        user_name = self.db_service.select_one_result('session', 'username')
        display = self.db_service.select_one_result('session', 'display')

        self.logger.debug('User : '******'Makineyi etki alanından çıkarmak için zorunlu alanları giriniz. Lütfen DEVAM EDEN İŞLEMLERİNİZİ sonlandırdığınıza emin olunuz !',
            'ETKI ALANINDAN ÇIKARMA')

        self.logger.debug('pout : ' + str(pout))

        field_values = pout.split(' ')

        user_registration_info = list(field_values)

        data = dict()
        data['type'] = 'UNREGISTER'
        data['from'] = str(self.conf_manager.get('CONNECTION', 'uid'))
        data['password'] = str(self.conf_manager.get('CONNECTION', 'password'))

        data['userName'] = user_registration_info[0]
        data['userPassword'] = user_registration_info[1]

        #data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
        #data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
        #data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
        # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Unregister message was created')
        return json_data
コード例 #4
0
ファイル: messaging.py プロジェクト: tncyclk/ahenk
    def policy_request_msg(self, username):
        data = dict()
        data['type'] = 'GET_POLICIES'

        user_policy_number = self.db_service.select_one_result(
            'policy', 'version',
            'type = \'U\' and name = \'' + username + '\'')
        machine_policy_number = self.db_service.select_one_result(
            'policy', 'version', 'type = \'A\'')

        user_policy_list = self.db_service.select(
            'policy', ['id', 'version', 'name', 'policy_id', 'assign_date'],
            ' type=\'U\' and name=\'' + username + '\'')
        # to add policy_id and policy_version
        user_policy_hash_list = dict()
        if len(user_policy_list) > 0:
            for i in range(len(user_policy_list)):
                user_policy_hash_list[str(user_policy_list[i][3])] = [
                    user_policy_list[i][1], user_policy_list[i][4]
                ]
        data['policyList'] = user_policy_hash_list

        data['userPolicyVersion'] = user_policy_number
        data['agentPolicyVersion'] = machine_policy_number

        data['username'] = str(username)
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Get Policies message was created')
        return json_data
コード例 #5
0
ファイル: messaging.py プロジェクト: tncyclk/ahenk
    def login_msg(self, username, ip=None):
        data = dict()
        data['type'] = 'LOGIN'
        data['username'] = username
        data['ipAddresses'] = str(
            System.Hardware.Network.ip_addresses()).replace('[', '').replace(
                ']', '')
        data['timestamp'] = Util.timestamp()
        data['userIp'] = ip
        data['osVersion'] = System.Os.version()
        data['diskTotal'] = System.Hardware.Disk.total()
        data['diskUsed'] = System.Hardware.Disk.used()
        data['diskFree'] = System.Hardware.Disk.free()
        data['memory'] = System.Hardware.Memory.total()
        data['hostname'] = str(System.Os.hostname())
        data['agentVersion'] = str(Util.get_agent_version())

        self.logger.debug('USER IP : ' + str(ip) + ' IPADDRESSES : ' +
                          str(System.Hardware.Network.ip_addresses()).replace(
                              '[', '').replace(']', ''))

        data['hardware.monitors'] = str(System.Hardware.monitors()),
        data['hardware.screens'] = str(System.Hardware.screens()),
        data['hardware.usbDevices'] = str(System.Hardware.usb_devices()),
        data['hardware.printers'] = str(System.Hardware.printers()),
        data['hardware.systemDefinitions'] = str(
            System.Hardware.system_definitions()),

        json_data = json.dumps(data)
        self.logger.debug('Login message was created')
        return json_data
コード例 #6
0
ファイル: messaging.py プロジェクト: Agem-Bilisim/ahenk
 def logout_msg(self, username):
     data = dict()
     data['type'] = 'LOGOUT'
     data['username'] = str(username)
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Logout message was created')
     return json_data
コード例 #7
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
 def logout_msg(self, username):
     data = dict()
     data['type'] = 'LOGOUT'
     data['username'] = str(username)
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Logout message was created')
     return json_data
コード例 #8
0
    def execute_script(self, arg):
        try:
            self.logger.debug('Executing script...')
            messenger = Scope().get_instance().get_messenger()

            json_data = json.loads(arg)
            result_code, p_out, p_err = Util.execute(str(json_data['command']))

            self.logger.debug('Executed script')

            data = dict()
            data['type'] = 'SCRIPT_RESULT'
            data['timestamp'] = str(Util.timestamp())

            if result_code == 0:
                self.logger.debug('Command execution was finished successfully')
                try:
                    temp_name = str(Util.generate_uuid())
                    temp_full_path = System.Ahenk.received_dir_path() + temp_name
                    self.logger.debug('Writing result to file')
                    Util.write_file(temp_full_path, str(p_out))
                    md5 = Util.get_md5_file(temp_full_path)
                    Util.rename_file(temp_full_path, System.Ahenk.received_dir_path() + md5)

                    file_manager = FileTransferManager(json_data['fileServerConf']['protocol'],
                                                       json_data['fileServerConf']['parameterMap'])
                    file_manager.transporter.connect()
                    self.logger.debug('File transfer connection was created')
                    success = file_manager.transporter.send_file(System.Ahenk.received_dir_path() + md5, md5)
                    self.logger.debug('File was transferred')
                    file_manager.transporter.disconnect()
                    self.logger.debug('File transfer connection was closed')

                    if success is False:
                        self.logger.error('A problem occurred while file transferring')
                        data['resultCode'] = '-1'
                        data[
                            'errorMessage'] = 'Command executed successfully but a problem occurred while sending result file'

                    else:
                        data['md5'] = md5

                except Exception as e:
                    self.logger.error(
                        'A problem occurred while file transferring. Error Message :{0}'.format(
                            str(e)))
                    raise
            else:
                self.logger.error(
                    'Command execution was failed. Error Message :{0}'.format(str(result_code)))
                data['resultCode'] = str(result_code)
                data['errorMessage'] = str(p_err)

            messenger.send_direct_message(json.dumps(data))
        except Exception as e:
            self.logger.error(
                'A problem occurred while running execute script action. Error Message :{0}'.format(
                    str(e)))
コード例 #9
0
    def execute_script(self, arg):
        try:
            self.logger.debug('Executing script...')
            messenger = Scope().get_instance().get_messenger()

            json_data = json.loads(arg)
            result_code, p_out, p_err = Util.execute(str(json_data['command']))

            self.logger.debug('Executed script')

            data = dict()
            data['type'] = 'SCRIPT_RESULT'
            data['timestamp'] = str(Util.timestamp())

            if result_code == 0:
                self.logger.debug('Command execution was finished successfully')
                try:
                    temp_name = str(Util.generate_uuid())
                    temp_full_path = System.Ahenk.received_dir_path() + temp_name
                    self.logger.debug('Writing result to file')
                    Util.write_file(temp_full_path, str(p_out))
                    md5 = Util.get_md5_file(temp_full_path)
                    Util.rename_file(temp_full_path, System.Ahenk.received_dir_path() + md5)

                    file_manager = FileTransferManager(json_data['fileServerConf']['protocol'],
                                                       json_data['fileServerConf']['parameterMap'])
                    file_manager.transporter.connect()
                    self.logger.debug('File transfer connection was created')
                    success = file_manager.transporter.send_file(System.Ahenk.received_dir_path() + md5, md5)
                    self.logger.debug('File was transferred')
                    file_manager.transporter.disconnect()
                    self.logger.debug('File transfer connection was closed')

                    if success is False:
                        self.logger.error('A problem occurred while file transferring')
                        data['resultCode'] = '-1'
                        data[
                            'errorMessage'] = 'Command executed successfully but a problem occurred while sending result file'

                    else:
                        data['md5'] = md5

                except Exception as e:
                    self.logger.error(
                        'A problem occurred while file transferring. Error Message :{0}'.format(
                            str(e)))
                    raise
            else:
                self.logger.error(
                    'Command execution was failed. Error Message :{0}'.format(str(result_code)))
                data['resultCode'] = str(result_code)
                data['errorMessage'] = str(p_err)

            messenger.send_direct_message(json.dumps(data))
        except Exception as e:
            self.logger.error(
                'A problem occurred while running execute script action. Error Message :{0}'.format(
                    str(e)))
コード例 #10
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
 def login_msg(self, username):
     data = dict()
     data['type'] = 'LOGIN'
     data['username'] = username
     data['ipAddresses'] = str(System.Hardware.Network.ip_addresses()).replace('[', '').replace(']', '')
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Login message was created')
     return json_data
コード例 #11
0
ファイル: messaging.py プロジェクト: Agem-Bilisim/ahenk
 def login_msg(self, username):
     data = dict()
     data['type'] = 'LOGIN'
     data['username'] = username
     data['ipAddresses'] = str(
         System.Hardware.Network.ip_addresses()).replace('[', '').replace(
             ']', '')
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Login message was created')
     return json_data
コード例 #12
0
ファイル: messaging.py プロジェクト: sezginbozu/ahenk
 def ldap_registration_msg(self):
     data = dict()
     data['type'] = 'REGISTER_LDAP'
     data['from'] = str(self.conf_manager.get('REGISTRATION', 'from'))
     data['password'] = str(self.conf_manager.get('REGISTRATION', 'password'))
     data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
     data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
     data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('LDAP Registration message was created')
     return json_data
コード例 #13
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
 def ldap_registration_msg(self):
     data = dict()
     data['type'] = 'REGISTER_LDAP'
     data['from'] = str(self.conf_manager.get('REGISTRATION', 'from'))
     data['password'] = str(self.conf_manager.get('REGISTRATION', 'password'))
     data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
     data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
     data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('LDAP Registration message was created')
     return json_data
コード例 #14
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
 def unregister_msg(self):
     data = dict()
     data['type'] = 'UNREGISTER'
     data['from'] = str(self.conf_manager.get('REGISTRATION', 'from'))
     data['password'] = str(self.conf_manager.get('REGISTRATION', 'password'))
     data['macAddresses'] = str(self.conf_manager.get('REGISTRATION', 'macAddresses'))
     data['ipAddresses'] = str(self.conf_manager.get('REGISTRATION', 'ipAddresses'))
     data['hostname'] = str(self.conf_manager.get('REGISTRATION', 'hostname'))
     # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Unregister message was created')
     return json_data
コード例 #15
0
ファイル: messaging.py プロジェクト: tncyclk/ahenk
    def agreement_request_msg(self):
        data = dict()
        data['type'] = 'REQUEST_AGREEMENT'
        """
        contract_content = self.db_service.select_one_result('contract', 'content', 'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''
        """

        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Agreement request message was created')
        return json_data
コード例 #16
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
    def agreement_request_msg(self):
        data = dict()
        data['type'] = 'REQUEST_AGREEMENT'

        """
        contract_content = self.db_service.select_one_result('contract', 'content', 'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''
        """

        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Agreement request message was created')
        return json_data
コード例 #17
0
ファイル: messaging.py プロジェクト: tncyclk/ahenk
    def agreement_answer_msg(self, username, answer):
        data = dict()
        data['type'] = 'AGREEMENT_STATUS'
        data['username'] = username
        data['accepted'] = answer
        data['timestamp'] = Util.timestamp()
        contract_content = self.db_service.select_one_result(
            'contract', 'content', 'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''

        json_data = json.dumps(data)
        self.logger.debug('Agreement answer message was created')
        return json_data
コード例 #18
0
ファイル: messaging.py プロジェクト: sezginbozu/ahenk
    def policy_request_msg(self, username):
        data = dict()
        data['type'] = 'GET_POLICIES'

        user_policy_number = self.db_service.select_one_result('policy', 'version',
                                                               'type = \'U\' and name = \'' + username + '\'')
        machine_policy_number = self.db_service.select_one_result('policy', 'version', 'type = \'A\'')

        data['userPolicyVersion'] = user_policy_number
        data['agentPolicyVersion'] = machine_policy_number

        data['username'] = str(username)
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Get Policies message was created')
        return json_data
コード例 #19
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
    def policy_request_msg(self, username):
        data = dict()
        data['type'] = 'GET_POLICIES'

        user_policy_number = self.db_service.select_one_result('policy', 'version',
                                                               'type = \'U\' and name = \'' + username + '\'')
        machine_policy_number = self.db_service.select_one_result('policy', 'version', 'type = \'A\'')

        data['userPolicyVersion'] = user_policy_number
        data['agentPolicyVersion'] = machine_policy_number

        data['username'] = str(username)
        data['timestamp'] = Util.timestamp()
        json_data = json.dumps(data)
        self.logger.debug('Get Policies message was created')
        return json_data
コード例 #20
0
ファイル: messaging.py プロジェクト: Pardus-Kurumsal/ahenk
    def agreement_answer_msg(self, username, answer):
        data = dict()
        data['type'] = 'AGREEMENT_STATUS'
        data['username'] = username
        data['accepted'] = answer
        data['timestamp'] = Util.timestamp()
        contract_content = self.db_service.select_one_result('contract', 'content',
                                                             'id =(select MAX(id) from contract)')
        if contract_content is not None and contract_content != '':
            data['md5'] = Util.get_md5_text(contract_content)
        else:
            data['md5'] = ''

        json_data = json.dumps(data)
        self.logger.debug('Agreement answer message was created')
        return json_data
コード例 #21
0
ファイル: messaging.py プロジェクト: Agem-Bilisim/ahenk
 def unregister_msg(self):
     data = dict()
     data['type'] = 'UNREGISTER'
     data['from'] = str(self.conf_manager.get('REGISTRATION', 'from'))
     data['password'] = str(
         self.conf_manager.get('REGISTRATION', 'password'))
     data['macAddresses'] = str(
         self.conf_manager.get('REGISTRATION', 'macAddresses'))
     data['ipAddresses'] = str(
         self.conf_manager.get('REGISTRATION', 'ipAddresses'))
     data['hostname'] = str(
         self.conf_manager.get('REGISTRATION', 'hostname'))
     # data['username'] = str(pwd.getpwuid( os.getuid() )[ 0 ])
     data['timestamp'] = Util.timestamp()
     json_data = json.dumps(data)
     self.logger.debug('Unregister message was created')
     return json_data
コード例 #22
0
    def login_msg(self, username):
        data = dict()
        data['type'] = 'LOGIN'
        data['username'] = username
        data['ipAddresses'] = str(
            System.Hardware.Network.ip_addresses()).replace('[', '').replace(
                ']', '')
        data['timestamp'] = Util.timestamp()

        data['hardware.monitors'] = str(System.Hardware.monitors()),
        data['hardware.screens'] = str(System.Hardware.screens()),
        data['hardware.usbDevices'] = str(System.Hardware.usb_devices()),
        data['hardware.printers'] = str(System.Hardware.printers()),
        data['hardware.systemDefinitions'] = str(
            System.Hardware.system_definitions()),

        json_data = json.dumps(data)
        self.logger.debug('Login message was created')
        return json_data
コード例 #23
0
    def run_command_from_fifo(self, num, stack):
        """ docstring"""

        while True:
            try:
                event = Commander().get_event()
                if event is None:
                    break
                json_data = json.loads(event)
            except Exception as e:
                self.logger.error(
                    'A problem occurred while loading json. Check json format! Error Message: {0}.'
                    ' Event = {1}'.format(str(e), str(event)))
                return

            if json_data is not None:

                self.logger.debug('Signal handled')
                self.logger.debug('Signal is :{0}'.format(str(json_data['event'])))

                if str(json_data['event']) == 'login':
                    username = json_data['username']
                    display = json_data['display']
                    desktop = json_data['desktop']
                    self.logger.info('login event is handled for user: {0}'.format(username))
                    login_message = self.message_manager.login_msg(username)
                    self.messenger.send_direct_message(login_message)

                    agreement = Agreement()
                    agreement_choice = None

                    if agreement.check_agreement(username) is not True:
                        self.logger.debug('User {0} has not accepted agreement.'.format(username))
                        thread_ask = Process(target=agreement.ask, args=(username, display,))
                        thread_ask.start()

                        agreement_timeout = self.conf_manager.get('SESSION', 'agreement_timeout')

                        timeout = int(agreement_timeout)  # sec
                        timer = time.time()
                        while 1:
                            if thread_ask.is_alive() is False:
                                self.logger.warning('{0} was answered the question '.format(username))
                                if Agreement().check_agreement(username) is True:
                                    self.logger.warning('Choice of {0} is YES'.format(username))
                                    agreement_choice = True
                                    break
                                elif Agreement().check_agreement(username) is False:
                                    self.logger.warning('Choice of {0} is NO'.format(username))
                                    agreement_choice = False
                                    Util.close_session(username)
                                    break

                            if (time.time() - timer) > timeout:
                                if thread_ask.is_alive():
                                    thread_ask.terminate()
                                Util.close_session(username)
                                self.logger.warning(
                                    'Session of {0} was ended because of timeout of contract agreement'.format(
                                        username))
                                break
                            time.sleep(1)

                        if agreement_choice is not None:
                            self.messenger.send_direct_message(
                                self.message_manager.agreement_answer_msg(username, agreement_choice))
                    else:
                        agreement_choice = True

                    if agreement_choice is True:
                        self.db_service.delete('session', 'username=\'{0}\''.format(username))

                        self.logger.info(
                            'Display is {0}, desktop env is {1} for {2}'.format(display, desktop,
                                                                                username))
                        session_columns = self.db_service.get_cols('session')
                        self.db_service.update('session', session_columns,
                                               [username, display, desktop, Util.timestamp()])
                        get_policy_message = self.message_manager.policy_request_msg(username)

                        self.plugin_manager.process_mode('safe', username)
                        self.plugin_manager.process_mode('login', username)

                        kward = dict()
                        kward['timeout_args'] = username
                        kward['checker_args'] = username

                        SetupTimer.start(Timer(timeout=System.Ahenk.get_policy_timeout(),
                                               timeout_function=self.execute_manager.execute_default_policy,
                                               checker_func=self.execute_manager.is_policy_executed, kwargs=kward))

                        self.logger.info(
                            'Requesting updated policies from Lider. If Ahenk could not reach updated '
                            'policies in {0} sec, booked policies will be executed'.format(
                                System.Ahenk.get_policy_timeout()))
                        self.messenger.send_direct_message(get_policy_message)

                elif str(json_data['event']) == 'logout':
                    username = json_data['username']
                    self.db_service.delete('session', 'username=\'{0}\''.format(username))
                    self.execute_manager.remove_user_executed_policy_dict(username)
                    # TODO delete all user records while initializing
                    self.logger.info('logout event is handled for user: {0}'.format(username))
                    logout_message = self.message_manager.logout_msg(username)
                    self.messenger.send_direct_message(logout_message)

                    self.plugin_manager.process_mode('logout', username)
                    self.plugin_manager.process_mode('safe', username)

                elif str(json_data['event']) == 'send':
                    self.logger.info('Sending message over ahenkd command. Response Message: {0}'.format(
                        json.dumps(json_data['message'])))
                    message = json.dumps(json_data['message'])
                    self.messenger.send_direct_message(message)

                elif str(json_data['event']) == 'load':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are loading to ahenk')
                        self.plugin_manager.load_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug('{0} plugin is loading to ahenk'.format(p_name))
                            self.plugin_manager.load_single_plugin(p_name)

                elif str(json_data['event']) == 'reload':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are reloading to ahenk')
                        self.plugin_manager.reload_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug('{0} plugin is reloading to ahenk'.format(p_name))
                            self.plugin_manager.reload_single_plugin(p_name)

                elif str(json_data['event']) == 'remove':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are removing from ahenk')
                        self.plugin_manager.remove_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug('{0} plugin is removing from ahenk'.format(p_name))
                            self.plugin_manager.remove_single_plugin(p_name)

                elif str(json_data['event']) == 'stop':
                    self.plugin_manager.process_mode('shutdown')
                    self.logger.info('Shutdown mode activated.')

                    # TODO timeout
                    while self.running_plugin() is False:
                        self.logger.debug('Waiting for progress of plugins...')
                        time.sleep(0.5)

                    Util.delete_file(System.Ahenk.fifo_file())
                    Scope().get_instance().get_custom_param('ahenk_daemon').stop()
                else:
                    self.logger.error('Unknown command error. Command:' + json_data['event'])
                self.logger.debug('Processing of handled event is completed')
コード例 #24
0
ファイル: command_runner.py プロジェクト: volkansahin/ahenk
    def run_command_from_fifo(self, num, stack):
        """ docstring"""

        while True:
            try:
                event = Commander().get_event()
                if event is None:
                    break
                json_data = json.loads(event)
            except Exception as e:
                self.logger.error(
                    'A problem occurred while loading json. Check json format! Error Message: {0}.'
                    ' Event = {1}'.format(str(e), str(event)))
                return

            if json_data is not None:

                self.logger.debug('Signal handled')
                self.logger.debug('Signal is :{0}'.format(
                    str(json_data['event'])))

                if str(json_data['event']) == 'login':
                    username = json_data['username']
                    display = json_data['display']
                    desktop = json_data['desktop']
                    self.logger.info(
                        'login event is handled for user: {0}'.format(
                            username))
                    login_message = self.message_manager.login_msg(username)
                    self.messenger.send_direct_message(login_message)

                    agreement = Agreement()
                    agreement_choice = None

                    if agreement.check_agreement(username) is not True:
                        self.logger.debug(
                            'User {0} has not accepted agreement.'.format(
                                username))
                        thread_ask = Process(target=agreement.ask,
                                             args=(
                                                 username,
                                                 display,
                                             ))
                        thread_ask.start()

                        agreement_timeout = self.conf_manager.get(
                            'SESSION', 'agreement_timeout')

                        timeout = int(agreement_timeout)  # sec
                        timer = time.time()
                        while 1:
                            if thread_ask.is_alive() is False:
                                self.logger.warning(
                                    '{0} was answered the question '.format(
                                        username))
                                if Agreement().check_agreement(
                                        username) is True:
                                    self.logger.warning(
                                        'Choice of {0} is YES'.format(
                                            username))
                                    agreement_choice = True
                                    break
                                elif Agreement().check_agreement(
                                        username) is False:
                                    self.logger.warning(
                                        'Choice of {0} is NO'.format(username))
                                    agreement_choice = False
                                    Util.close_session(username)
                                    break

                            if (time.time() - timer) > timeout:
                                if thread_ask.is_alive():
                                    thread_ask.terminate()
                                Util.close_session(username)
                                self.logger.warning(
                                    'Session of {0} was ended because of timeout of contract agreement'
                                    .format(username))
                                break
                            time.sleep(1)

                        if agreement_choice is not None:
                            self.messenger.send_direct_message(
                                self.message_manager.agreement_answer_msg(
                                    username, agreement_choice))
                    else:
                        agreement_choice = True

                    if agreement_choice is True:
                        self.db_service.delete(
                            'session', 'username=\'{0}\''.format(username))

                        self.logger.info(
                            'Display is {0}, desktop env is {1} for {2}'.
                            format(display, desktop, username))
                        session_columns = self.db_service.get_cols('session')
                        self.db_service.update(
                            'session', session_columns,
                            [username, display, desktop,
                             Util.timestamp()])
                        get_policy_message = self.message_manager.policy_request_msg(
                            username)

                        self.plugin_manager.process_mode('safe', username)
                        self.plugin_manager.process_mode('login', username)

                        kward = dict()
                        kward['timeout_args'] = username
                        kward['checker_args'] = username

                        SetupTimer.start(
                            Timer(timeout=System.Ahenk.get_policy_timeout(),
                                  timeout_function=self.execute_manager.
                                  execute_default_policy,
                                  checker_func=self.execute_manager.
                                  is_policy_executed,
                                  kwargs=kward))

                        self.logger.info(
                            'Requesting updated policies from Lider. If Ahenk could not reach updated '
                            'policies in {0} sec, booked policies will be executed'
                            .format(System.Ahenk.get_policy_timeout()))
                        self.messenger.send_direct_message(get_policy_message)

                elif str(json_data['event']) == 'logout':
                    username = json_data['username']
                    self.db_service.delete('session',
                                           'username=\'{0}\''.format(username))
                    self.execute_manager.remove_user_executed_policy_dict(
                        username)
                    # TODO delete all user records while initializing
                    self.logger.info(
                        'logout event is handled for user: {0}'.format(
                            username))
                    logout_message = self.message_manager.logout_msg(username)
                    self.messenger.send_direct_message(logout_message)

                    self.plugin_manager.process_mode('logout', username)
                    self.plugin_manager.process_mode('safe', username)

                elif str(json_data['event']) == 'send':
                    self.logger.info(
                        'Sending message over ahenkd command. Response Message: {0}'
                        .format(json.dumps(json_data['message'])))
                    message = json.dumps(json_data['message'])
                    self.messenger.send_direct_message(message)

                elif str(json_data['event']) == 'load':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are loading to ahenk')
                        self.plugin_manager.load_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is loading to ahenk'.format(
                                    p_name))
                            self.plugin_manager.load_single_plugin(p_name)

                elif str(json_data['event']) == 'reload':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug('All plugins are reloading to ahenk')
                        self.plugin_manager.reload_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is reloading to ahenk'.format(
                                    p_name))
                            self.plugin_manager.reload_single_plugin(p_name)

                elif str(json_data['event']) == 'remove':
                    plugin_name = str(json_data['plugins'])

                    if plugin_name == 'all':
                        self.logger.debug(
                            'All plugins are removing from ahenk')
                        self.plugin_manager.remove_plugins()
                    else:
                        for p_name in plugin_name.split(','):
                            self.logger.debug(
                                '{0} plugin is removing from ahenk'.format(
                                    p_name))
                            self.plugin_manager.remove_single_plugin(p_name)

                elif str(json_data['event']) == 'stop':
                    self.plugin_manager.process_mode('shutdown')
                    self.logger.info('Shutdown mode activated.')

                    # TODO timeout
                    while self.running_plugin() is False:
                        self.logger.debug('Waiting for progress of plugins...')
                        time.sleep(0.5)

                    Util.delete_file(System.Ahenk.fifo_file())
                    Scope().get_instance().get_custom_param(
                        'ahenk_daemon').stop()
                else:
                    self.logger.error('Unknown command error. Command:' +
                                      json_data['event'])
                self.logger.debug('Processing of handled event is completed')