def get_configs_handler(self, message, command_id, user_data,
                            command_connection, closed=False):
        req_id = user_data
        try:
            data_connection = self.get_configs_map[command_id]
        except:
            err_msg = 'AgentListener: Failed sending agent GET_CONFIGS response.'
            err_msg += '\ndata_connection object not found for command_id: %s' %\
                        command_id
            err_msg += '\nDumping get_configs_map dict:\n'
            err_msg += '%s' % str(self.get_configs_map)
            logging.error(err_msg, exc_info=True)
            return

        if closed:
            err_msg = 'AgentListener: Failed GET_CONFIGS from agent.\n'
            err_msg += 'Connection closed by agent.'
            logging.warning(err_msg)
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        if command_id not in self.get_configs_map.keys():
            err_msg = 'AgentListener: GET_CONFIGS agent request with invalid id'
            logging.warning(err_msg)
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        configs = message
        response = ServerInterface.build_accepted_response(req_id)
        body = dict()
        body[AgentGetConfigsResponseBody.configs] = configs
        response[ResponseFields.body] = body
        data_connection.send_message(json.dumps(response), True)
    def evaluate_restart_request(self, agent_request, req_id, data_connection):
        # Check the format is correct
        restart_request = AgentRestartRequest(agent_request)
        if not restart_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Make sure the agent tracker is up
        hostname = restart_request.get_hostname()
        if self.agent_tracker is None or self.command_tracker is None:
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Check the host is tracked
        if not self.agent_tracker.have_host(hostname):
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Try sending the command
        command_id = self.command_tracker.send_command(hostname,\
                'GENERAL', 'RESTART')
        if command_id is -1:
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
        else:
            response = ServerInterface.build_accepted_response(req_id)
            data_connection.send_message(json.dumps(response), True)
    def evaluate_get_configs_request(self, agent_request, req_id,\
                                     data_connection):
        get_configs_request = AgentGetConfigsRequest(agent_request)
        # Check the format is correct
        if not get_configs_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Make sure the agent tracker is up
        hostname = get_configs_request.get_hostname()
        if self.agent_tracker is None or self.command_tracker is None:
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Check the host is tracked
        if not self.agent_tracker.have_host(hostname):
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        command_id = self.command_tracker.send_command(hostname,\
                'GENERAL', 'GET_CONFIGS',\
                handler_function=self.get_configs_handler,\
                handler_user_data=req_id)

        # If we failed sending the command
        if command_id is -1:
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
        else:
            self.get_configs_map[command_id] = data_connection
    def evaluate_set_configs_request(self, agent_request, req_id,\
                                     data_connection):
        # Check the format is correct
        set_configs_request = AgentSetConfigsRequest(agent_request)
        if not set_configs_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Make sure the agent tracker is up
        hostname = set_configs_request.get_hostname()
        if self.agent_tracker is None or self.command_tracker is None:
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Check the host is tracked
        if not self.agent_tracker.have_host(hostname):
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        # Try sending the command
        configs = set_configs_request.get_configs()
        
        command_sent = self.command_tracker.send_command(hostname,\
                'GENERAL', 'SET_CONFIGS', command_body=configs)
        if not command_sent:
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
        else:
            response = ServerInterface.build_accepted_response(req_id)
            data_connection.send_message(json.dumps(response), True)
    def evaluate_del_user_request(self, agent_request, req_id, data_connection):
        del_user_request = AgentDelUserRequest(agent_request)
        if not del_user_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        username = del_user_request.get_username()
        self.del_user(username)
        response = ServerInterface.build_accepted_response(req_id)
        data_connection.send_message(json.dumps(response), True)
    def evaluate_add_user_request(self, agent_request, req_id, data_connection):
        add_user_request = AgentAddUserRequest(agent_request)
        if not add_user_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        username = add_user_request.get_username()
        password = add_user_request.get_password()
        logging.info('########## %s %s', username, password)
        self.add_user(username, password)
        response = ServerInterface.build_accepted_response(req_id)
        data_connection.send_message(json.dumps(response), True)
    def __init__(self, configs):
        logging.info('Initializing ServerCore ...')

        self.initialized = True
        self.configs = configs
        try:
            self.database = Database(configs)
        except:
            logging.critical('Failed to initialize ServerCore. Shutting down.',
                             exc_info=True)
            self.initialized = False
            return
        
        if self.database.database is None:
            logging.critical('Failed to initialize ServerCore. Shutting down.')
            self.initialized = False
            return
        self.shell = ServerShell(self)
        self.database.shell = self.shell

        self.modules = {}
        self._load_modules()
        
        self.user_system = UserSystem(self.database)
        self.server_interface = ServerInterface(self.configs,
                                                self.user_system, self.shell)
        self.shell.server_interface = self.server_interface

        # Initialize the Notification system
        Notification.registered_classes[Notification.get_name()] = Notification

        # Save the configs
        self.configs.save_settings()

        logging.info('Initialized ServerCore')
    def evaluate_get_users_request(self, agent_request, req_id, data_connection):
        usernames = self.users.keys()

        response = ServerInterface.build_accepted_response(req_id)
        body = dict()
        body[AgentGetUsersResponseBody.usernames] = usernames
        response[ResponseFields.body] = body
        data_connection.send_message(json.dumps(response), True)
    def handle_real_time_close(self, device_sensor_request, req_id,
                               data_connection):
        close_request = DeviceSensorRealTimeClose(device_sensor_request)
        if not close_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        original_req_id = close_request.get_request_id()
        gui_hostname = data_connection.peer_host
        try:
            command_id = self.active_command_connections[(gui_hostname,
                                                          original_req_id)]
            agent_hostname = device_sensor_request.get_agent_hostname()
            self.command_tracker.close_command_connection(agent_hostname,
                                                          command_id)
        except:
            pass

        response = ServerInterface.build_accepted_response(req_id)
        data_connection.send_message(json.dumps(response), True)
    def evaluate_request(self, request, data_connection):
        logging.debug('DeviceSensor: Evaluating request ...')
        
        req_id = request.get_request_id()
        device_sensor_request = DeviceSensorRequest(request)
        if not device_sensor_request.sanity_check():
            logging.warning('DeviceSensor: Invalid request')
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        if self.command_tracker is None:
            logging.warning('DeviceSensor: CommandTracker not found')
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        request_type = device_sensor_request.get_type()
        try:
            self.request_handlers[request_type](device_sensor_request, req_id,
                                                data_connection)
        except:
            logging.warning('DeviceSensor: Invalid request type', exc_info=True)
    def evaluate_request(self, request, data_connection):
        req_id = request.get_request_id()
    
        agent_request = AgentRequest(request)

        if not agent_request.sanity_check():
            response = ServerInterface.build_invalid_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        request_type = agent_request.get_type()
        try:
            self.request_handlers[request_type](agent_request, req_id,\
                                                data_connection)
        except:
            logging.warning('AgentListener: Invalid request type', exc_info=True)
    def handle_real_time_request(self, device_sensor_request, req_id,
                                 data_connection):
        agent_hostname = device_sensor_request.get_agent_hostname()

        command_id = self.command_tracker.send_command(
            agent_hostname, 'DeviceSensor', 'REAL_TIME_REQUEST',
            handler_function=self.real_time_command_callback,
            handler_user_data=data_connection)

        if command_id is None:
            logging.warning('DeviceSensor: Error sending command')
            response = ServerInterface.build_internal_error_response(req_id)
            data_connection.send_message(json.dumps(response), True)
            return

        gui_hostname = data_connection.peer_host
        self.active_command_connections[(gui_hostname, req_id)] =\
            command_id
    def real_time_command_callback(self, message, command_id,
        handler_user_data, command_connection, closed=False):
        if closed:
            logging.debug('DeviceSensor: Command Connection %d closed',
                          command_id)
            message = dict()
            message['state'] = 'DOWN'
        else:
            message['state'] = 'UP'

        response = ServerInterface.build_accepted_response(-1)
        response[ResponseFields.response_type] = 'DEVICE_SENSOR_REAL_TIME_REQUEST'
        response[ResponseFields.body] = message

        data_connection = handler_user_data
        sent_ok = data_connection.send_message(json.dumps(response), True)

        # Check the requesting application didn't went down
        if not sent_ok:
            return False

        return True
Exemple #14
0
class ServerCore:

    def __init__(self, configs):
        logging.info('Initializing ServerCore ...')

        self.initialized = True
        self.configs = configs
        try:
            self.database = Database(configs)
        except:
            logging.critical('Failed to initialize ServerCore. Shutting down.',
                             exc_info=True)
            self.initialized = False
            return
        
        if self.database.database is None:
            logging.critical('Failed to initialize ServerCore. Shutting down.')
            self.initialized = False
            return
        self.shell = ServerShell(self)
        self.database.shell = self.shell

        self.modules = {}
        self._load_modules()
        
        self.user_system = UserSystem(self.database)
        self.server_interface = ServerInterface(self.configs,
                                                self.user_system, self.shell)
        self.shell.server_interface = self.server_interface

        # Initialize the Notification system
        Notification.registered_classes[Notification.get_name()] = Notification

        # Save the configs
        self.configs.save_settings()

        logging.info('Initialized ServerCore')


    def set_admin_password(self, password):
        if not self.initialized:
            return False
        self.user_system.set_admin_password(password)
        return True


    def _load_modules(self):
        logging.info('Loading modules ...')
        modules_objects =\
            umit.inventory.common.load_modules_from_target('server',
                self.configs, self.shell)
        for module_object in modules_objects:
            self.modules[module_object.get_name()] = module_object
        logging.info('Loaded modules')


    def _activate_modules(self):
        # Init subscriptions. This is done now because all modules must be
        # loaded and initialized before the subscribtions are done.
        logging.info('Initializing modules subscriptions ...')
        for module in self.modules.values():
            if not module.is_enabled():
                continue
            if isinstance(module, SubscriberServerModule):
                module.subscribe()
        logging.info('Initialized modules subscriptions.')

        # Init the database operations for each module.
        logging.info('Initializing modules database operations ...')
        for module in self.modules.values():
            module.init_database_operations()
        logging.info('Done initializing modules database operations.')

        # Activate the modules
        logging.info('Activating modules ...')
        for module in self.modules.values():
            if module.is_enabled():
                module.activate()
        logging.info('Done activating modules.')


    def update_configs(self, configs):
        try:
            logging.info('Updating configurations.\n%s',
                         json.dumps(configs, sort_keys=True, indent=4))
        except:
            logging.warning('Invalid configuration change request',
                            exc_info=True)

        try:
            sections = configs.keys()
            for section in sections:
                options = configs[section]
                for option_name in options.keys():
                    option_value = options[option_name]
                    self.configs.set(section, option_name, option_value)

                # If a module, refresh it's settings and activate if needed
                if section in self.modules.keys():
                    module = self.modules[section]
                    if not module.is_enabled() and\
                       self.configs.get(section, InventoryConfig.module_enabled):
                        module.activate()
                    module.refresh_settings()

            # Save the settings
            self.configs.save_settings()
        except:
            logging.error('Changing server configurations failed',
                          exc_info=True)


    def run(self):
        if not self.initialized:
            return
        
        self._activate_modules()

        # Call the modules which implement ListenerServerModule so they
        # will start listening.
        for module in self.modules.values():
            if not module.is_enabled():
                continue
            if isinstance(module, ListenerServerModule):
                module.listen()
        self.server_interface.listen()
        
        logging.info('Starting the Twisted Reactor')
        reactor.run()


    def shutdown(self):
        for module in self.modules.values():
            if module.is_enabled():
                module.deactivate()
            module.shutdown()
        reactor.stop()