示例#1
0
def qeb_hwt_thamos_advise() -> None:
    """Qeb-Hwt Thamos Advise Task."""
    if not Configuration._REPO_PATH:
        raise Exception(
            f"No path has been provided to REPO_PATH env variable.")

    if not Path(Configuration._REPO_PATH).exists():
        raise FileNotFoundError(
            f"Cannot find the file on this path: {Configuration._REPO_PATH}")

    OpenShift.verify_github_app_inputs(
        github_event_type=Configuration._GITHUB_EVENT_TYPE,
        github_check_run_id=Configuration._GITHUB_CHECK_RUN_ID,
        github_installation_id=Configuration._GITHUB_INSTALLATION_ID,
        github_base_repo_url=Configuration._GITHUB_BASE_REPO_URL,
        origin=Configuration._ORIGIN,
    )

    os.chdir(Configuration._REPO_PATH)
    thoth_yaml_config = _Configuration()

    if not thoth_yaml_config.config_file_exists():
        exception_message = _create_message_config_file_error(no_file=True)
        trigger_finished_webhook(exception_message=exception_message,
                                 has_error=True,
                                 error_type="MissingThothYamlFile")
        return

    # Fetch recommedation type
    try:
        thoth_yaml_runtime_env = thoth_yaml_config.content.get(
            "runtime_environments")
        recommendation_type = thoth_yaml_runtime_env[0].get(
            "recommendation_type") if thoth_yaml_config else "latest"

        requirements_format = thoth_yaml_config.requirements_format
        if requirements_format == "pipenv":
            project = Project.from_files(
                without_pipfile_lock=not os.path.exists("Pipfile.lock"))
        elif requirements_format in ("pip", "pip-tools", "pip-compile"):
            project = Project.from_pip_compile_files(allow_without_lock=True)
        else:
            raise ValueError(
                f"Unknown configuration option for requirements format: {requirements_format!r}"
            )

        pipfile = project.pipfile.to_string()
        pipfile_lock_str = project.pipfile_lock.to_string(
        ) if project.pipfile_lock else ""
        application_stack = PythonStack(
            requirements=pipfile,
            requirements_lock=pipfile_lock_str,
            requirements_format=requirements_format).to_dict()
    except Exception as exception:
        _LOGGER.debug(json.loads(exception.body)["error"])  # type: ignore
        exception_message = json.loads(exception.body)["error"]  # type: ignore
        trigger_finished_webhook(exception_message=exception_message,
                                 has_error=True)
        return

    # The input for AdviserTriggerMessage if no exceptions were found
    message_input = {
        "component_name": {
            "type": "str",
            "value": __COMPONENT_NAME__
        },
        "service_version": {
            "type": "str",
            "value": __service_version__
        },
        "application_stack": {
            "type": "Dict",
            "value": application_stack
        },
        "recommendation_type": {
            "type": "str",
            "value": recommendation_type
        },
        "github_event_type": {
            "type": "str",
            "value": Configuration._GITHUB_EVENT_TYPE
        },
        "github_check_run_id": {
            "type": "int",
            "value": int(Configuration._GITHUB_CHECK_RUN_ID)
        },
        "github_installation_id": {
            "type": "int",
            "value": int(Configuration._GITHUB_INSTALLATION_ID)
        },
        "github_base_repo_url": {
            "type": "str",
            "value": Configuration._GITHUB_BASE_REPO_URL
        },
        "origin": {
            "type": "str",
            "value": Configuration._ORIGIN
        },
        "source_type": {
            "type": "str",
            "value": ThothAdviserIntegrationEnum.GITHUB_APP.name
        },
    }

    # We store the message to put in the output file here.
    message_output = [{
        "topic_name": "thoth.adviser-trigger",
        "message_contents": message_input
    }]

    # Store message to file that need to be sent.
    with open(f"/mnt/workdir/messages_to_be_sent.json", "w") as json_file:
        json.dump(message_output, json_file)

    if message_output:
        _LOGGER.info(
            f"Successfully stored file with messages to be sent!: {message_output}"
        )
示例#2
0
def qeb_hwt_thamos_advise() -> None:
    """Qeb-Hwt Thamos Advise Task."""
    if not Configuration._REPO_PATH:
        raise Exception(
            f"No path has been provided to REPO_PATH env variable.")

    if not Path(Configuration._REPO_PATH).exists():
        raise FileNotFoundError(
            f"Cannot find the file on this path: {Configuration._REPO_PATH}")

    OpenShift.verify_github_app_inputs(
        github_event_type=Configuration._GITHUB_EVENT_TYPE,
        github_check_run_id=Configuration._GITHUB_CHECK_RUN_ID,
        github_installation_id=Configuration._GITHUB_INSTALLATION_ID,
        github_base_repo_url=Configuration._GITHUB_BASE_REPO_URL,
        origin=Configuration._ORIGIN,
    )

    os.chdir(Configuration._REPO_PATH)
    thoth_yaml_config = _Configuration()

    if not thoth_yaml_config.config_file_exists():
        exception_message = _create_message_config_file_error(no_file=True)
        trigger_finished_webhook(exception_message=exception_message,
                                 has_error=True,
                                 error_type="MissingThothYamlFile")
        return

    try:
        analysis_id = advise_here(
            nowait=True,
            github_event_type=Configuration._GITHUB_EVENT_TYPE,
            github_check_run_id=Configuration._GITHUB_CHECK_RUN_ID,
            github_installation_id=Configuration._GITHUB_INSTALLATION_ID,
            github_base_repo_url=Configuration._GITHUB_BASE_REPO_URL,
            origin=Configuration._ORIGIN,
            source_type=ThothAdviserIntegrationEnum.GITHUB_APP,
        )
        _LOGGER.info("Successfully submitted thamos advise call: %r",
                     analysis_id)
    except Exception as exception:
        if isinstance(
                exception,
            (
                NoRuntimeEnvironmentError,
                NoRequirementsFormatError,
                FileNotFoundError,
                FileLoadError,
                KeyError,
                ValueError,
                AttributeError,
            ),
        ):
            _LOGGER.debug(exception)
            exception_message = str(exception)
        else:
            _LOGGER.debug(json.loads(exception.body)["error"])  # type: ignore
            exception_message = json.loads(
                exception.body)["error"]  # type: ignore

        trigger_finished_webhook(exception_message=exception_message,
                                 has_error=True)