Beispiel #1
0
def _find_connection_locally(ctx, connection_name):
    # check that the provided path points to a proper connection directory -> look for connection.yaml file.
    # first check in aea dir
    registry_path = ctx.agent_config.registry_path
    connection_configuration_filepath = Path(os.path.join(registry_path, "connections", connection_name, DEFAULT_CONNECTION_CONFIG_FILE))
    if not connection_configuration_filepath.exists():
        # then check in registry
        registry_path = AEA_DIR
        connection_configuration_filepath = Path(os.path.join(registry_path, "connections", connection_name, DEFAULT_CONNECTION_CONFIG_FILE))
        if not connection_configuration_filepath.exists():
            logger.error("Cannot find connection: '{}'.".format(connection_name))
            sys.exit(1)

    # try to load the connection configuration file
    try:
        connection_configuration = ctx.connection_loader.load(open(str(connection_configuration_filepath)))
        logger.info("Connection '{}' supports the following protocols: {}".format(connection_name, connection_configuration.restricted_to_protocols))
    except ValidationError as e:
        logger.error("Connection configuration file not valid: {}".format(str(e)))
        sys.exit(1)

    # copy the connection package into the agent's supported connections.
    src = str(Path(os.path.join(registry_path, "connections", connection_name)).absolute())
    dest = os.path.join(ctx.cwd, "connections", connection_name)
    logger.debug("Copying connection modules. src={} dst={}".format(src, dest))
    try:
        shutil.copytree(src, dest)
    except Exception as e:
        logger.error(str(e))
        sys.exit(1)
Beispiel #2
0
def install(ctx: Context, requirement: Optional[str]):
    """Install the dependencies."""
    _try_to_load_agent_config(ctx)

    if requirement:
        logger.debug(
            "Installing the dependencies in '{}'...".format(requirement))
        dependencies = list(
            map(lambda x: x.strip(),
                open(requirement).readlines()))
    else:
        logger.debug("Installing all the dependencies...")
        dependencies = ctx.get_dependencies()

    for d in dependencies:
        logger.info("Installing {}...".format(d))
        try:
            subp = subprocess.Popen(
                [sys.executable, "-m", "pip", "install", d])
            subp.wait(30.0)
            assert subp.returncode == 0
        except Exception:
            logger.error(
                "An error occurred while installing {}. Stopping...".format(d))
            sys.exit(1)
Beispiel #3
0
def skill(click_context, skill_name):
    """Add a skill to the agent."""
    ctx = cast(Context, click_context.obj)
    agent_name = ctx.agent_config.agent_name

    is_registry = ctx.config.get("is_registry")
    if is_registry:
        public_id = str(skill_name)
        skill_name = split_public_id(skill_name)[1]

    logger.info("Adding skill '{}' to the agent '{}'...".format(skill_name, agent_name))

    # check if we already have a skill with the same name
    logger.debug("Skills already supported by the agent: {}".format(ctx.agent_config.skills))
    if skill_name in ctx.agent_config.skills:
        logger.error("A skill with name '{}' already exists. Aborting...".format(skill_name))
        sys.exit(1)

    # find and add protocol
    if is_registry:
        # fetch from Registry
        fetch_package('skill', public_id=public_id, cwd=ctx.cwd)
    else:
        _find_skill_locally(ctx, skill_name, click_context)

    # make the 'skills' folder a Python package.
    skills_init_module = os.path.join(ctx.cwd, "skills", "__init__.py")
    logger.debug("Creating {}".format(skills_init_module))
    Path(skills_init_module).touch(exist_ok=True)

    # add the skill to the configurations.
    logger.debug("Registering the skill into {}".format(DEFAULT_AEA_CONFIG_FILE))
    ctx.agent_config.skills.add(skill_name)
    ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))
Beispiel #4
0
def delete(ctx: Context, agent_name):
    """Delete an agent."""
    path = Path(agent_name)

    # check that the target folder is an AEA project.
    cwd = os.getcwd()
    try:
        os.chdir(agent_name)
        fp = open(DEFAULT_AEA_CONFIG_FILE, mode="r", encoding="utf-8")
        ctx.agent_config = ctx.agent_loader.load(fp)
        _try_to_load_agent_config(ctx)
    except Exception:
        logger.error("The name provided is not an AEA project.")
        sys.exit(1)
    finally:
        os.chdir(cwd)

    logger.info("Deleting agent project directory '/{}'...".format(path))

    # delete the agent's directory
    try:
        shutil.rmtree(path, ignore_errors=False)
    except OSError:
        logger.error(
            "An error occurred while deleting the agent directory. Aborting..."
        )
        sys.exit(1)
Beispiel #5
0
def protocol(ctx: Context, protocol_name):
    """Remove a protocol from the agent."""
    agent_name = ctx.agent_config.agent_name
    logger.info(
        "Removing protocol {protocol_name} from the agent {agent_name}...".
        format(agent_name=agent_name, protocol_name=protocol_name))

    if protocol_name not in ctx.agent_config.protocols:
        logger.error("Protocol '{}' not found.".format(protocol_name))
        exit(-1)

    protocol_folder = os.path.join("protocols", protocol_name)
    try:
        shutil.rmtree(protocol_folder)
    except BaseException:
        logger.exception("An error occurred.")
        exit(-1)

    # removing the protocol to the configurations.
    logger.debug(
        "Removing the protocol from {}".format(DEFAULT_AEA_CONFIG_FILE))
    if protocol_name in ctx.agent_config.protocols:
        ctx.agent_config.protocols.remove(protocol_name)
        ctx.agent_loader.dump(ctx.agent_config,
                              open(DEFAULT_AEA_CONFIG_FILE, "w"))
Beispiel #6
0
def connection(ctx: Context, connection_name):
    """Remove a connection from the agent."""
    agent_name = ctx.agent_config.agent_name
    logger.info(
        "Removing connection {connection_name} from the agent {agent_name}...".
        format(agent_name=agent_name, connection_name=connection_name))

    if connection_name not in ctx.agent_config.connections:
        logger.error("Connection '{}' not found.".format(connection_name))
        exit(-1)

    connection_folder = os.path.join("connections", connection_name)
    try:
        shutil.rmtree(connection_folder)
    except BaseException:
        logger.exception(
            "An error occurred while deleting '{}'.".format(connection_folder))
        exit(-1)

    # removing the connection to the configurations.
    logger.debug(
        "Removing the connection from {}".format(DEFAULT_AEA_CONFIG_FILE))
    if connection_name in ctx.agent_config.connections:
        ctx.agent_config.connections.remove(connection_name)
        ctx.agent_loader.dump(ctx.agent_config,
                              open(DEFAULT_AEA_CONFIG_FILE, "w"))
Beispiel #7
0
def connection(click_context, connection_name):
    """Add a connection to the configuration file."""
    ctx = cast(Context, click_context.obj)
    agent_name = ctx.agent_config.agent_name

    is_registry = ctx.config.get("is_registry")
    if is_registry:
        public_id = str(connection_name)
        connection_name = split_public_id(connection_name)[1]

    logger.info("Adding connection '{}' to the agent '{}'...".format(connection_name, agent_name))

    # check if we already have a connection with the same name
    logger.debug("Connections already supported by the agent: {}".format(ctx.agent_config.connections))
    if connection_name in ctx.agent_config.connections:
        logger.error("A connection with name '{}' already exists. Aborting...".format(connection_name))
        sys.exit(1)

    # find and add connection
    if is_registry:
        # fetch from Registry
        fetch_package('connection', public_id=public_id, cwd=ctx.cwd)
    else:
        _find_connection_locally(ctx, connection_name)

    # make the 'connections' folder a Python package.
    connections_init_module = os.path.join(ctx.cwd, "connections", "__init__.py")
    logger.debug("Creating {}".format(connections_init_module))
    Path(connections_init_module).touch(exist_ok=True)

    # add the connections to the configurations.
    logger.debug("Registering the connection into {}".format(DEFAULT_AEA_CONFIG_FILE))
    ctx.agent_config.connections.add(connection_name)
    ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))
Beispiel #8
0
def skill(click_context, skill_name):
    """Add a skill to the agent."""
    ctx = cast(Context, click_context.obj)
    agent_name = ctx.agent_config.agent_name
    logger.debug("Adding skill {} to the agent {}...".format(skill_name, agent_name))

    # check if we already have a skill with the same name
    logger.debug("Skills already supported by the agent: {}".format(ctx.agent_config.skills))
    if skill_name in ctx.agent_config.skills:
        logger.error("A skill with name '{}' already exists. Aborting...".format(skill_name))
        exit(-1)

    # check that the provided path points to a proper skill directory -> look for skill.yaml file.
    # first check in aea dir
    registry_path = ctx.agent_config.registry_path
    skill_configuration_filepath = Path(os.path.join(registry_path, "skills", skill_name, DEFAULT_SKILL_CONFIG_FILE))
    if not skill_configuration_filepath.exists():
        # then check in registry
        registry_path = AEA_DIR
        skill_configuration_filepath = Path(os.path.join(registry_path, "skills", skill_name, DEFAULT_SKILL_CONFIG_FILE))
        if not skill_configuration_filepath.exists():
            logger.error("Cannot find skill: '{}'.".format(skill_name))
            exit(-1)

    # try to load the skill configuration file
    try:
        skill_configuration = ctx.skill_loader.load(open(str(skill_configuration_filepath)))
    except ValidationError as e:
        logger.error("Skill configuration file not valid: {}".format(str(e)))
        exit(-1)

    # copy the skill package into the agent's supported skills.
    src = str(Path(os.path.join(registry_path, "skills", skill_name)).absolute())
    dest = os.path.join(ctx.cwd, "skills", skill_name)
    logger.info("Copying skill modules. src={} dst={}".format(src, dest))
    try:
        shutil.copytree(src, dest)
    except Exception as e:
        logger.error(str(e))
        exit(-1)

    # make the 'skills' folder a Python package.
    skills_init_module = os.path.join(ctx.cwd, "skills", "__init__.py")
    logger.debug("Creating {}".format(skills_init_module))
    Path(skills_init_module).touch(exist_ok=True)

    # check for not supported protocol, and add it.
    for protocol_name in skill_configuration.protocols:
        if protocol_name not in ctx.agent_config.protocols:
            logger.info("Adding protocol '{}' to the agent...".format(protocol_name))
            click_context.invoke(protocol, protocol_name=protocol_name)

    # add the skill to the configurations.
    logger.debug("Registering the skill into {}".format(DEFAULT_AEA_CONFIG_FILE))
    ctx.agent_config.skills.add(skill_name)
    ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))
Beispiel #9
0
def delete(ctx: Context, agent_name):
    """Delete an agent."""
    path = Path(agent_name)
    logger.info("Deleting agent's directory in '{}'...".format(path))

    # delete the agent's directory
    try:
        shutil.rmtree(path, ignore_errors=False)
    except OSError:
        logger.error("An error occurred while deleting the agent directory. Aborting...")
        exit(-1)
Beispiel #10
0
def run(click_context, connection_names: List[str], env_file: str,
        install_deps: bool):
    """Run the agent."""
    ctx = cast(Context, click_context.obj)
    _try_to_load_agent_config(ctx)
    _load_env_file(env_file)
    agent_name = cast(str, ctx.agent_config.agent_name)

    _verify_or_create_private_keys(ctx)
    _verify_ledger_apis_access()
    private_key_paths = dict([(identifier, config.path)
                              for identifier, config in
                              ctx.agent_config.private_key_paths.read_all()])
    ledger_api_configs = dict([
        (identifier, (config.addr, config.port))
        for identifier, config in ctx.agent_config.ledger_apis.read_all()
    ])

    wallet = Wallet(private_key_paths)
    ledger_apis = LedgerApis(ledger_api_configs)

    connection_names = [ctx.agent_config.default_connection
                        ] if connection_names is None else connection_names
    connections = []
    _try_to_load_protocols(ctx)
    try:
        for connection_name in connection_names:
            connection = _setup_connection(connection_name,
                                           wallet.public_keys[FETCHAI], ctx)
            connections.append(connection)
    except AEAConfigException as e:
        logger.error(str(e))
        sys.exit(1)

    if install_deps:
        if Path("requirements.txt").exists():
            click_context.invoke(install, requirement="requirements.txt")
        else:
            click_context.invoke(install)

    agent = AEA(agent_name,
                connections,
                wallet,
                ledger_apis,
                resources=Resources(str(Path("."))))
    try:
        agent.start()
    except KeyboardInterrupt:
        logger.info("Interrupted.")  # pragma: no cover
    except Exception as e:
        logger.exception(e)
        sys.exit(1)
    finally:
        agent.stop()
Beispiel #11
0
def connection(click_context, connection_name):
    """Add a connection to the configuration file."""
    ctx = cast(Context, click_context.obj)
    agent_name = ctx.agent_config.agent_name
    logger.debug("Adding connection {} to the agent {}...".format(connection_name, agent_name))

    # check if we already have a connection with the same name
    logger.debug("Connection already supported by the agent: {}".format(ctx.agent_config.connections))
    if connection_name in ctx.agent_config.connections:
        logger.error("A connection with name '{}' already exists. Aborting...".format(connection_name))
        exit(-1)

    # check that the provided path points to a proper connection directory -> look for connection.yaml file.
    # first check in aea dir
    registry_path = ctx.agent_config.registry_path
    connection_configuration_filepath = Path(os.path.join(registry_path, "connections", connection_name, DEFAULT_CONNECTION_CONFIG_FILE))
    if not connection_configuration_filepath.exists():
        # then check in registry
        registry_path = AEA_DIR
        connection_configuration_filepath = Path(os.path.join(registry_path, "connections", connection_name, DEFAULT_CONNECTION_CONFIG_FILE))
        if not connection_configuration_filepath.exists():
            logger.error("Cannot find connection: '{}'.".format(connection_name))
            exit(-1)

    # try to load the connection configuration file
    try:
        connection_configuration = ctx.connection_loader.load(open(str(connection_configuration_filepath)))
        logger.info("Connection supports the following protocols: {}".format(connection_configuration.supported_protocols))
    except ValidationError as e:
        logger.error("Connection configuration file not valid: {}".format(str(e)))
        exit(-1)

    # copy the connection package into the agent's supported connections.
    src = str(Path(os.path.join(registry_path, "connections", connection_name)).absolute())
    dest = os.path.join(ctx.cwd, "connections", connection_name)
    logger.info("Copying connection modules. src={} dst={}".format(src, dest))
    try:
        shutil.copytree(src, dest)
    except Exception as e:
        logger.error(str(e))
        exit(-1)

    # make the 'connections' folder a Python package.
    connections_init_module = os.path.join(ctx.cwd, "connections", "__init__.py")
    logger.debug("Creating {}".format(connections_init_module))
    Path(connections_init_module).touch(exist_ok=True)

    # add the connections to the configurations.
    logger.debug("Registering the connection into {}".format(DEFAULT_AEA_CONFIG_FILE))
    ctx.agent_config.connections.add(connection_name)
    ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))
Beispiel #12
0
def protocol(click_context, protocol_name):
    """Add a protocol to the agent."""
    ctx = cast(Context, click_context.obj)
    agent_name = cast(str, ctx.agent_config.agent_name)
    logger.debug("Adding protocol {} to the agent {}...".format(protocol_name, agent_name))

    # check if we already have a protocol with the same name
    logger.debug("Protocols already supported by the agent: {}".format(ctx.agent_config.protocols))
    if protocol_name in ctx.agent_config.protocols:
        logger.error("A protocol with name '{}' already exists. Aborting...".format(protocol_name))
        exit(-1)

    # check that the provided path points to a proper protocol directory -> look for protocol.yaml file.
    # first check in aea dir
    registry_path = ctx.agent_config.registry_path
    protocol_configuration_filepath = Path(os.path.join(registry_path, "protocols", protocol_name, DEFAULT_PROTOCOL_CONFIG_FILE))
    if not protocol_configuration_filepath.exists():
        # then check in registry
        registry_path = AEA_DIR
        protocol_configuration_filepath = Path(os.path.join(registry_path, "protocols", protocol_name, DEFAULT_PROTOCOL_CONFIG_FILE))
        if not protocol_configuration_filepath.exists():
            logger.error("Cannot find protocol: '{}'.".format(protocol_name))
            exit(-1)

    # try to load the protocol configuration file
    try:
        protocol_configuration = ctx.protocol_loader.load(open(str(protocol_configuration_filepath)))
        logger.info("Protocol available: {}".format(protocol_configuration.name))
    except ValidationError as e:
        logger.error("Protocol configuration file not valid: {}".format(str(e)))
        exit(-1)
        return

    # copy the protocol package into the agent's supported connections.
    src = str(Path(os.path.join(registry_path, "protocols", protocol_name)).absolute())
    dest = os.path.join(ctx.cwd, "protocols", protocol_name)
    logger.info("Copying protocol modules. src={} dst={}".format(src, dest))
    try:
        shutil.copytree(src, dest)
    except Exception as e:
        logger.error(str(e))
        exit(-1)

    # make the 'protocols' folder a Python package.
    logger.debug("Creating {}".format(os.path.join(agent_name, "protocols", "__init__.py")))
    Path(os.path.join(ctx.cwd, "protocols", "__init__.py")).touch(exist_ok=True)

    # add the protocol to the configurations.
    logger.debug("Registering the protocol into {}".format(DEFAULT_AEA_CONFIG_FILE))
    ctx.agent_config.protocols.add(protocol_name)
    ctx.agent_loader.dump(ctx.agent_config, open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))
Beispiel #13
0
def protocol(ctx: Context, protocol_name: str):
    """Add a protocol scaffolding to the configuration file and agent."""
    # check if we already have a protocol with the same name
    logger.debug("Protocols already supported by the agent: {}".format(
        ctx.agent_config.protocols))
    if protocol_name in ctx.agent_config.protocols:
        logger.error(
            "A protocol with name '{}' already exists. Aborting...".format(
                protocol_name))
        exit(-1)
        return

    try:
        # create the 'protocols' folder if it doesn't exist:
        if not os.path.exists("protocols"):
            os.makedirs("protocols")

        # create the protocol folder
        dest = Path(os.path.join("protocols", protocol_name))

        # copy the skill package into the agent's supported skills.
        src = Path(os.path.join(AEA_DIR, "protocols", "scaffold"))
        logger.info("Copying protocol modules. src={} dst={}".format(
            src, dest))
        try:
            shutil.copytree(src, dest)
        except Exception as e:
            logger.error(e)
            exit(-1)

        # add the protocol to the configurations.
        logger.info(
            "Registering the protocol into {}".format(DEFAULT_AEA_CONFIG_FILE))
        ctx.agent_config.protocols.add(protocol_name)
        ctx.agent_loader.dump(
            ctx.agent_config,
            open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))

    except OSError:
        logger.error("Directory already exist. Aborting...")
        exit(-1)
    except ValidationError as e:
        logger.error(str(e))
        shutil.rmtree(protocol_name, ignore_errors=True)
        exit(-1)
    except Exception as e:
        logger.exception(e)
        shutil.rmtree(protocol_name, ignore_errors=True)
        exit(-1)
Beispiel #14
0
def create(click_context, agent_name):
    """Create an agent."""
    ctx = cast(Context, click_context.obj)
    path = Path(agent_name)
    logger.info("Initializing AEA project '{}'".format(agent_name))
    logger.info("Creating project directory '/{}'".format(agent_name))

    # create the agent's directory
    try:
        path.mkdir(exist_ok=False)

        # create a config file inside it
        logger.info("Creating config file {}".format(DEFAULT_AEA_CONFIG_FILE))
        config_file = open(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE),
                           "w")
        agent_config = AgentConfig(agent_name=agent_name,
                                   aea_version=aea.__version__,
                                   authors="",
                                   version="v1",
                                   license="",
                                   url="",
                                   registry_path=DEFAULT_REGISTRY_PATH,
                                   description="")
        agent_config.default_connection = DEFAULT_CONNECTION
        ctx.agent_loader.dump(agent_config, config_file)

        # next commands must be done from the agent's directory -> overwrite ctx.cwd
        ctx.agent_config = agent_config
        ctx.cwd = agent_config.agent_name

        logger.info("Default connections:")
        click_context.invoke(connection, connection_name=DEFAULT_CONNECTION)

        logger.info("Default skills:")
        click_context.invoke(skill, skill_name=DEFAULT_SKILL)

    except OSError:
        logger.error("Directory already exist. Aborting...")
        sys.exit(1)
    except ValidationError as e:
        logger.error(str(e))
        shutil.rmtree(agent_name, ignore_errors=True)
        sys.exit(1)
    except Exception as e:
        logger.exception(e)
        shutil.rmtree(agent_name, ignore_errors=True)
        sys.exit(1)
Beispiel #15
0
def run(ctx: Context, connection_name: str):
    """Run the agent."""
    _try_to_load_agent_config(ctx)
    agent_name = cast(str, ctx.agent_config.agent_name)
    private_key_pem_path = cast(str, ctx.agent_config.private_key_pem_path)
    if private_key_pem_path == "":
        private_key_pem_path = _create_temporary_private_key_pem_path()
    else:
        _try_validate_private_key_pem_path(private_key_pem_path)
    crypto = Crypto(private_key_pem_path=private_key_pem_path)
    public_key = crypto.public_key
    connection_name = ctx.agent_config.default_connection if connection_name is None else connection_name
    _try_to_load_protocols(ctx)
    try:
        connection = _setup_connection(connection_name, public_key, ctx)
    except AEAConfigException as e:
        logger.error(str(e))
        exit(-1)
        return

    logger.debug("Installing all the dependencies...")
    for d in ctx.get_dependencies():
        logger.debug("Installing {}...".format(d))
        try:
            subp = subprocess.Popen(
                [sys.executable, "-m", "pip", "install", d])
            subp.wait(30.0)
        except Exception:
            logger.error(
                "An error occurred while installing {}. Stopping...".format(d))
            exit(-1)

    mailbox = MailBox(connection)
    agent = AEA(agent_name,
                mailbox,
                private_key_pem_path=private_key_pem_path,
                directory=str(Path(".")))
    try:
        agent.start()
    except KeyboardInterrupt:
        logger.info("Interrupted.")
    except Exception as e:
        logger.exception(e)
    finally:
        agent.stop()
Beispiel #16
0
def skill(ctx: Context, skill_name):
    """Remove a skill from the agent."""
    agent_name = ctx.agent_config.agent_name
    logger.info("Removing skill '{skill_name}' from the agent '{agent_name}'..."
                .format(agent_name=agent_name, skill_name=skill_name))

    if skill_name not in ctx.agent_config.skills:
        logger.error("The skill '{}' is not supported.".format(skill_name))
        sys.exit(1)

    skill_folder = os.path.join("skills", skill_name)
    try:
        shutil.rmtree(skill_folder)
    except BaseException:
        logger.exception("An error occurred.")
        sys.exit(1)

    # removing the protocol to the configurations.
    logger.debug("Removing the skill from {}".format(DEFAULT_AEA_CONFIG_FILE))
    if skill_name in ctx.agent_config.skills:
        ctx.agent_config.skills.remove(skill_name)
        ctx.agent_loader.dump(ctx.agent_config, open(DEFAULT_AEA_CONFIG_FILE, "w"))
Beispiel #17
0
def launch(click_context, agents: List[str]):
    """Launch many agents."""
    agents_directories = list(map(Path, list(OrderedDict.fromkeys(agents))))
    agent_processes = [
        Process(target=_run_agent, args=(click_context, agent_directory))
        for agent_directory in agents_directories
    ]

    failed = 0
    try:
        for agent_directory, agent_process in zip(agents_directories,
                                                  agent_processes):
            agent_process.start()
            logger.info("Agent {} started...".format(agent_directory.name))
        for agent_process in agent_processes:
            agent_process.join()
            failed |= (agent_process.exitcode
                       if agent_process.exitcode is not None else 1)
    except KeyboardInterrupt:
        # at this point, the keyboard interrupt has been propagated
        # to all the child process, hence we just need to 'join' the processes.
        for agent_directory, agent_process in zip(agents_directories,
                                                  agent_processes):
            logger.info("Waiting for agent {} to shut down...".format(
                agent_directory.name))
            agent_process.join(5.0)
            if agent_process.is_alive():
                logger.info("Killing agent {}...".format(agent_directory.name))
                agent_process.kill()
                failed = 1
            else:
                logger.info("Agent {} terminated with exit code {}".format(
                    agent_directory.name, agent_process.exitcode))
                failed |= (agent_process.exitcode
                           if agent_process.exitcode is not None else 1)
    except Exception as e:
        logger.exception(e)
        sys.exit(1)

    sys.exit(1) if failed else sys.exit(0)
Beispiel #18
0
def _launch_subprocesses(click_context: click.Context, agents: List[Path]):
    """
    Launch many agents using subprocesses.

    :param agents: list of paths to agent projects.
    :return: None
    """
    ctx = cast(Context, click_context.obj)
    processes = []
    failed = 0
    for agent_directory in agents:
        process = Popen(  # nosec
            [sys.executable, "-m", "aea.cli", "-v", ctx.verbosity, "run"],
            cwd=str(agent_directory),
        )
        logger.info("Agent {} started...".format(agent_directory.name))
        processes.append(process)

    try:
        for process in processes:
            process.wait()
    except KeyboardInterrupt:
        logger.info("Keyboard interrupt detected.")
    finally:
        for agent_directory, process in zip(agents, processes):
            result = process.poll()
            if result is None:
                try:
                    process.wait()
                except (subprocess.TimeoutExpired, KeyboardInterrupt):
                    logger.info("Force shutdown {}...".format(
                        agent_directory.name))
                    process.kill()

            logger.info("Agent {} terminated with exit code {}".format(
                agent_directory.name, process.returncode))
            failed |= process.returncode if process.returncode is not None else -1

    sys.exit(failed)
Beispiel #19
0
def create(click_context, agent_name):
    """Create an agent."""
    ctx = cast(Context, click_context.obj)
    path = Path(agent_name)
    logger.info("Creating agent's directory in '{}'".format(path))

    # create the agent's directory
    try:
        path.mkdir(exist_ok=False)

        # create a config file inside it
        config_file = open(os.path.join(agent_name, DEFAULT_AEA_CONFIG_FILE), "w")
        agent_config = AgentConfig(agent_name=agent_name, aea_version=aea.__version__, authors="", version="v1", license="", url="", registry_path="../packages", private_key_pem_path="")
        agent_config.default_connection = DEFAULT_CONNECTION
        ctx.agent_loader.dump(agent_config, config_file)
        logger.info("Created config file {}".format(DEFAULT_AEA_CONFIG_FILE))

        # next commands must be done from the agent's directory -> overwrite ctx.cwd
        ctx.agent_config = agent_config
        ctx.cwd = agent_config.agent_name

        logger.info("Adding default connection '{}' to the agent...".format(DEFAULT_CONNECTION))
        click_context.invoke(connection, connection_name=DEFAULT_CONNECTION)

        logger.info("Adding default skill '{}' to the agent...".format(DEFAULT_SKILL))
        click_context.invoke(skill, skill_name=DEFAULT_SKILL)

    except OSError:
        logger.error("Directory already exist. Aborting...")
        exit(-1)
    except ValidationError as e:
        logger.error(str(e))
        shutil.rmtree(agent_name, ignore_errors=True)
        exit(-1)
    except Exception as e:
        logger.exception(e)
        shutil.rmtree(agent_name, ignore_errors=True)
        exit(-1)
Beispiel #20
0
def _scaffold_item(ctx: Context, item_type, item_name):
    """Add an item scaffolding to the configuration file and agent."""
    existing_item_list = getattr(ctx.agent_config, "{}s".format(item_type))
    loader = getattr(ctx, "{}_loader".format(item_type))
    default_config_filename = globals()["DEFAULT_{}_CONFIG_FILE".format(
        item_type.upper())]

    item_type_plural = item_type + "s"

    # check if we already have an item with the same name
    logger.debug("{} already supported by the agent: {}".format(
        item_type_plural, existing_item_list))
    if item_name in existing_item_list:
        logger.error("A {} with name '{}' already exists. Aborting...".format(
            item_type, item_name))
        sys.exit(1)

    try:
        agent_name = ctx.agent_config.agent_name
        logger.info("Adding {} scaffold '{}' to the agent '{}'...".format(
            item_type, item_name, agent_name))

        Path(item_type_plural).mkdir(exist_ok=True)

        # create the connection folder
        dest = Path(os.path.join(item_type_plural, item_name))

        # copy the skill package into the agent's supported skills.
        src = Path(os.path.join(AEA_DIR, item_type_plural, "scaffold"))
        logger.debug("Copying {} modules. src={} dst={}".format(
            item_type, src, dest))

        shutil.copytree(src, dest)

        # add the connection to the configurations.
        logger.debug("Registering the {} into {}".format(
            item_type, DEFAULT_AEA_CONFIG_FILE))
        existing_item_list.add(item_name)
        ctx.agent_loader.dump(
            ctx.agent_config,
            open(os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE), "w"))

        # ensure the name in the yaml and the name of the folder are the same
        config_filepath = os.path.join(ctx.cwd, item_type_plural, item_name,
                                       default_config_filename)
        config = loader.load(open(str(config_filepath)))
        config.name = item_name
        loader.dump(config, open(config_filepath, "w"))

    except FileExistsError:
        logger.error(
            "A {} with this name already exists. Please choose a different name and try again."
            .format(item_type))
        sys.exit(1)
    except ValidationError:
        logger.error("Error when validating the skill configuration file.")
        shutil.rmtree(os.path.join(item_type_plural, item_name),
                      ignore_errors=True)
        sys.exit(1)
    except Exception as e:
        logger.exception(e)
        shutil.rmtree(os.path.join(item_type_plural, item_name),
                      ignore_errors=True)
        sys.exit(1)
Beispiel #21
0
def gui(ctx: Context, port):
    """Run the CLI GUI."""
    import aea.cli_gui  # pragma: no cover
    logger.info(
        "Running the GUI.....(press Ctrl+C to exit)")  # pragma: no cover
    aea.cli_gui.run(port)  # pragma: no cover