Exemplo n.º 1
0
    def _load_config_from_database(self,
                                   profile: str = 'Default') -> Dict[str, str]:
        """
        Loads a configuration profile from the database.

        :param profile: the name of the configuration profile

        :return Dict[str, str]: the configuration

        """
        config = {}

        db_handler = ResourceAdapterConfigDbHandler()

        try:
            db_config = db_handler.get(self.session, self.__adaptername__,
                                       profile)

            cfg_list = ResourceAdapterConfigSchema().dump(db_config).data

            for s in cfg_list['configuration']:
                config[s['key']] = s['value']
        except ResourceNotFound:
            pass

        return config
Exemplo n.º 2
0
    def _local_delete(self, resource_adapter_name: str,
                      resource_adapter_profile: str, cloudserver_id: str):
        from tortuga.db.models.instanceMapping import InstanceMapping
        from tortuga.db.models.instanceMetadata import InstanceMetadata
        from tortuga.db.resourceAdapterConfigDbHandler import ResourceAdapterConfigDbHandler
        from tortuga.node.nodeApi import NodeApi

        node_api = NodeApi()

        #
        # Assume the node instance ID name is the last item in the
        # delimited cloud server ID
        #
        instance = cloudserver_id.split(":")[-1]

        #
        # Lookup the resource adapter configuration profile...
        #
        rac_api = ResourceAdapterConfigDbHandler()
        rac = rac_api.get(self._sess, resource_adapter_name,
                          resource_adapter_profile)

        #
        # Check the instance mapping to see if there is a matching
        # instance id...
        #
        im_list = self._sess.query(InstanceMapping).filter(
            InstanceMapping.instance == instance,
            InstanceMapping.resource_adapter_configuration_id == rac.id)
        #
        # Found something? Delete it and then return...
        #
        for im in im_list:
            node = im.node
            node_api.deleteNode(self._sess, node.name)

        #
        # Check the instance metadata so see if there is a
        # matching vm_name...
        #
        im_list = self._sess.query(InstanceMetadata).filter(
            InstanceMetadata.key == "vm_name",
            InstanceMetadata.value == instance)
        #
        # Found something? Delete it and then return...
        #
        for im in im_list:
            if im.instance.resource_adapter_configuration_id != rac.id:
                continue
            node = im.instance.node
            node_api.deleteNode(self._sess, node.name)
def test_get(dbm):
    """
    Get 'default' resource adapter configuration for resource adapter 'aws'
    """

    with dbm.session() as session:
        result = ResourceAdapterConfigDbHandler().get(
            session, 'aws', 'default')

        assert result
Exemplo n.º 4
0
    def load_resource_adapter_config(self, session: Session,
                                     name: Optional[str] = None) \
            -> ResourceAdapterConfig:
        """
        Helper method to get resource adapter configuration

        Raises:
            ResourceNotFound
        """

        return ResourceAdapterConfigDbHandler().get(
            session,
            self.__adaptername__,
            name if name else 'Default',
        )
Exemplo n.º 5
0
    def load_resource_adapter_config(self, session: Session,
                                     name: Optional[str] = None) \
            -> ResourceAdapterConfig:
        """
        Helper method to get resource adapter configuration

        Raises:
            ResourceNotFound
        """

        return ResourceAdapterConfigDbHandler().get(
            session,
            self.__adaptername__,
            name if name else DEFAULT_CONFIGURATION_PROFILE_NAME,
        )
Exemplo n.º 6
0
    def __init__(self):
        self._resourceAdapterConfigDbHandler = \
            ResourceAdapterConfigDbHandler()

        self._resourceAdaptersDbHandler = ResourceAdaptersDbHandler()
Exemplo n.º 7
0
class ResourceAdapterConfigurationManager:
    def __init__(self):
        self._resourceAdapterConfigDbHandler = \
            ResourceAdapterConfigDbHandler()

        self._resourceAdaptersDbHandler = ResourceAdaptersDbHandler()

    def create(self,
               session: Session,
               resadapter_name: str,
               name: str,
               configuration: Union[List[Dict[str, str]], None] = None,
               force: bool = False) -> ResourceAdapterConfig:
        """
        Creates a new resource adapter profile.

        :param Session session:                    the current database
                                                   session
        :param str resadapter_name:                the name of the resource
                                                   adapter
        :param str name:                           the name of the resource
                                                   adapter profile
        :param List[Dict[str, str]] configuration: the list of configuration
                                                   settings
        :param bool force:                         when True, will not
                                                   validate the configuration
                                                   settings

        :raises ResourceAlreadyExists:
        :raises ResourceAdapterNotFound:
        :raises ValidationError:

        """
        #
        # Check for duplicates
        #
        adapter = self._resourceAdaptersDbHandler.getResourceAdapter(
            session, resadapter_name)

        try:
            self._resourceAdapterConfigDbHandler.get(session, resadapter_name,
                                                     name)
            raise ResourceAlreadyExists(
                'Resource adapter configuration [{}] already exists'.format(
                    name))

        except ResourceNotFound:
            pass

        #
        # Basic validation of the settings
        #
        cfg = ResourceAdapterConfig(name=name)
        validator = ConfigurationValidator(adapter.settings)

        for entry in configuration or []:
            cfg.configuration.append(
                ResourceAdapterSetting(key=entry['key'], value=entry['value']))
            validator[entry['key']] = entry['value']

        if not force:
            validator.validate(full=False)

        #
        # Commit resource adapter changes to database
        #
        adapter.resource_adapter_config.append(cfg)
        session.commit()

        return cfg

    def get(self, session: Session, resadapter_name: str, name: str) \
            -> ResourceAdapterConfig:
        """
        Raises:
            ResourceNotFound
            ResourceAdapterNotFound
        """

        # first check if resource adapter exists
        self._resourceAdaptersDbHandler.getResourceAdapter(
            session, resadapter_name)

        # then attempt to retrieve specified configuration
        return self._resourceAdapterConfigDbHandler.get(
            session, resadapter_name, name)

    def get_profile_names(self, session: Session, resadapter_name: str) \
            -> List[str]:
        """
        Raises:
            ResourceAdapterNotFound
        """

        adapter = self._resourceAdaptersDbHandler.getResourceAdapter(
            session, resadapter_name)

        return [cfg.name for cfg in adapter.resource_adapter_config]

    def delete(self, session: Session, resadapter_name: str, name: str) \
            -> None:
        """
        Delete resource adapter configuration

        Raises:
            ResourceAdapterNotFound
            ResourceNotFound
        """

        self._resourceAdaptersDbHandler.getResourceAdapter(
            session, resadapter_name)

        cfg = self.get(session, resadapter_name, name)

        session.delete(cfg)

    def update(self,
               session: Session,
               resadapter_name: str,
               name: str,
               configuration: List[Dict[str, str]],
               force: bool = False) -> None:
        """
        Updates an existing resource adapter profile.

        :param Session session:                    the current database
                                                   session
        :param str resadapter_name:                the name of the resource
                                                   adapter
        :param str name:                           the name of the resource
                                                   adapter profile
        :param List[Dict[str, str]] configuration: the list of configuration
                                                   settings
        :param bool force:                         when True, will not
                                                   validate the configuration
                                                   settings

        :raises ResourceAlreadyExists:
        :raises ResourceAdapterNotFound:
        :raises ValidationError:

        """
        #
        # Ensure resource adapter is valid
        #
        adapter = self._resourceAdaptersDbHandler.getResourceAdapter(
            session, resadapter_name)

        #
        # Basic validation of the settings
        #
        if not force:
            validator = ConfigurationValidator(adapter.settings)

            for entry in configuration or []:
                validator[entry['key']] = entry['value']

            validator.validate(full=False)

        #
        # Update the database
        #
        cfg = self._resourceAdapterConfigDbHandler.get(session,
                                                       resadapter_name, name)
        self.__update_settings(session, configuration, cfg.configuration)
        session.commit()

    def __update_settings(self, session: Session,
                          configuration: List[Dict[str, str]],
                          existing_settings: List[ResourceAdapterSetting]) \
            -> None:
        new_settings: List[Tuple[str, str]] = []
        delete_settings: List[ResourceAdapterSetting] = []

        for entry in configuration:
            if 'key' not in entry or 'value' not in entry:
                raise InvalidArgument(
                    'Malformed resource adapter configuration data')

            setting = setting_exists(existing_settings, entry['key'])

            if entry['value'] is None:
                if setting:
                    # setting is marked for deletion
                    delete_settings.append(setting)

                continue

            if setting is None:
                if entry['value'] is not None:
                    # create new setting
                    new_settings.append((entry['key'], entry['value']))

                continue

            # update existing settings
            setting.value = entry['value']

        # add new setting(s)
        for key, value in new_settings:
            existing_settings.append(
                ResourceAdapterSetting(key=key, value=value))

        # delete setting(s) marked for deletion
        for delete_setting in delete_settings:
            session.delete(delete_setting)
def test_get_failed(dbm):
    with dbm.session() as session:
        with pytest.raises(ResourceNotFound):
            ResourceAdapterConfigDbHandler().get(
                session, 'nonexistent', 'default')