Esempio n. 1
0
    def from_config(cls, configuration: ContractConfig,
                    **kwargs) -> "Contract":
        """
        Load contract from configuration.

        :param configuration: the contract configuration.
        :return: the contract object.
        """
        if configuration.directory is None:  # pragma: nocover
            raise ValueError(
                "Configuration must be associated with a directory.")
        directory = configuration.directory
        load_aea_package(configuration)
        contract_module = load_module(CONTRACTS, directory / "contract.py")
        classes = inspect.getmembers(contract_module, inspect.isclass)
        contract_class_name = cast(str, configuration.class_name)
        contract_classes = list(
            filter(lambda x: re.match(contract_class_name, x[0]), classes))
        name_to_class = dict(contract_classes)
        _default_logger.debug(f"Processing contract {contract_class_name}")
        contract_class = name_to_class.get(contract_class_name, None)
        if contract_class is None:
            raise AEAComponentLoadException(
                f"Contract class '{contract_class_name}' not found.")

        _try_to_register_contract(configuration)
        contract = contract_registry.make(str(configuration.public_id),
                                          **kwargs)
        return contract
Esempio n. 2
0
    def from_config(
        cls,
        configuration: ConnectionConfig,
        identity: Identity,
        crypto_store: CryptoStore,
        data_dir: str,
        **kwargs: Any,
    ) -> "Connection":
        """
        Load a connection from a configuration.

        :param configuration: the connection configuration.
        :param identity: the identity object.
        :param crypto_store: object to access the connection crypto objects.
        :param data_dir: the directory of the AEA project data.
        :return: an instance of the concrete connection class.
        """
        configuration = cast(ConnectionConfig, configuration)
        directory = cast(Path, configuration.directory)
        load_aea_package(configuration)
        connection_module_path = directory / "connection.py"
        if not (connection_module_path.exists() and connection_module_path.is_file()):
            raise AEAComponentLoadException(
                "Connection module '{}' not found.".format(connection_module_path)
            )
        connection_module = load_module(
            "connection_module", directory / "connection.py"
        )
        classes = inspect.getmembers(connection_module, inspect.isclass)
        connection_class_name = cast(str, configuration.class_name)
        connection_classes = list(
            filter(lambda x: re.match(connection_class_name, x[0]), classes)
        )
        name_to_class = dict(connection_classes)
        logger = get_logger(__name__, identity.name)
        logger.debug("Processing connection {}".format(connection_class_name))
        connection_class = name_to_class.get(connection_class_name, None)
        if connection_class is None:
            raise AEAComponentLoadException(
                "Connection class '{}' not found.".format(connection_class_name)
            )
        try:
            connection = connection_class(
                configuration=configuration,
                data_dir=data_dir,
                identity=identity,
                crypto_store=crypto_store,
                **kwargs,
            )
        except Exception as e:  # pragma: nocover # pylint: disable=broad-except
            e_str = parse_exception(e)
            raise AEAInstantiationException(
                f"An error occured during instantiation of connection {configuration.public_id}/{configuration.class_name}:\n{e_str}"
            )
        return connection
Esempio n. 3
0
    def from_config(
        cls, configuration: SkillConfig, agent_context: AgentContext, **kwargs
    ) -> "Skill":
        """
        Load the skill from configuration.

        :param configuration: a skill configuration. Must be associated with a directory.
        :param agent_context: the agent context.
        :return: the skill.
        """

        if configuration.directory is None:  # pragma: nocover
            raise ValueError("Configuration must be associated with a directory.")

        # we put the initialization here because some skill components
        # might need some info from the skill
        # (e.g. see https://github.com/fetchai/agents-aea/issues/1095)
        skill_context = SkillContext()
        skill_context.set_agent_context(agent_context)
        logger_name = f"aea.packages.{configuration.author}.skills.{configuration.name}"
        logger_name = _get_aea_logger_name_prefix(logger_name, agent_context.agent_name)
        _logger = AgentLoggerAdapter(
            logging.getLogger(logger_name), agent_context.agent_name
        )
        skill_context.logger = cast(Logger, _logger)

        skill = Skill(configuration, skill_context, **kwargs)

        directory = configuration.directory
        load_aea_package(configuration)
        handlers_by_id = dict(configuration.handlers.read_all())
        handlers = Handler.parse_module(
            str(directory / "handlers.py"), handlers_by_id, skill_context
        )

        behaviours_by_id = dict(configuration.behaviours.read_all())
        behaviours = Behaviour.parse_module(
            str(directory / "behaviours.py"), behaviours_by_id, skill_context,
        )

        models_by_id = dict(configuration.models.read_all())
        model_instances = Model.parse_module(
            str(directory), models_by_id, skill_context
        )

        skill.handlers.update(handlers)
        skill.behaviours.update(behaviours)
        skill.models.update(model_instances)

        return skill
Esempio n. 4
0
    def from_config(cls, configuration: ProtocolConfig,
                    **kwargs) -> "Protocol":
        """
        Load the protocol from configuration.

        :param configuration: the protocol configuration.
        :return: the protocol object.
        """
        if configuration.directory is None:  # pragma: nocover
            raise ValueError(
                "Configuration must be associated with a directory.")
        load_aea_package(configuration)
        class_module = importlib.import_module(
            configuration.prefix_import_path + ".message")
        classes = inspect.getmembers(class_module, inspect.isclass)
        name_camel_case = "".join(word.capitalize()
                                  for word in configuration.name.split("_"))
        message_classes = list(
            filter(
                lambda x: re.match("{}Message".format(name_camel_case), x[0]),
                classes))
        enforce(
            len(message_classes) == 1,
            "Not exactly one message class detected.")
        message_class = message_classes[0][1]
        class_module = importlib.import_module(
            configuration.prefix_import_path + ".serialization")
        classes = inspect.getmembers(class_module, inspect.isclass)
        serializer_classes = list(
            filter(
                lambda x: re.match("{}Serializer".format(name_camel_case), x[0]
                                   ),
                classes,
            ))
        enforce(
            len(serializer_classes) == 1,
            "Not exactly one serializer class detected.")
        serialize_class = serializer_classes[0][1]
        message_class.serializer = serialize_class

        return Protocol(configuration, message_class, **kwargs)
Esempio n. 5
0
def test_load_aea_package():
    """Test aea package load."""
    config = ConnectionConfig("http_client", "fetchai", "0.5.0")
    config.directory = Path(ROOT_DIR) / "packages"
    load_aea_package(config)