Example #1
0
    def _run_step(self):
        """Runs the step implemented by this StepImplementer.

        Returns
        -------
        StepResult
            Object containing the dictionary results of this step.
        """
        step_result = StepResult.from_step_implementer(self)

        username = None
        password = None
        token = None

        if self.has_config_value(AUTHENTICATION_CONFIG, True):
            # Optional: token
            if self.get_value('token'):
                token = self.get_value('token')
            # Optional: username and password
            else:
                if (self.get_value('username')
                        and self.get_value('password')):
                    username = self.get_value('username')
                    password = self.get_value('password')

        application_name = self.get_value('application-name')
        service_name = self.get_value('service-name')
        properties_file = self.get_value('properties')

        # Optional: project-key
        if self.get_value('project-key'):
            project_key = self.get_value('project-key')
        # Default
        else:
            project_key = f'{application_name}:{service_name}'

        if not os.path.exists(properties_file):
            step_result.success = False
            step_result.message = f'Properties file not found: {properties_file}'
            return step_result

        sonarqube_success = False
        try:
            # Hint:  Call sonar-scanner with sh.sonar_scanner
            #    https://amoffat.github.io/sh/sections/faq.html
            working_directory = self.work_dir_path

            sonar_optional_flags = []
            # determine auth flags
            if token:
                sonar_optional_flags += [
                    f'-Dsonar.login={token}'
                ]
            elif username:
                sonar_optional_flags += [
                    f'-Dsonar.login={username}',
                    f'-Dsonar.password={password}',
                ]

            # determine branch flag
            # only provide sonar.branch.name flag if not the "main"/"master"/"release branch" and
            # sonar-analyze-branches is true (since can only due with certain versions of SonarQube)
            # see: https://community.sonarsource.com/t/how-to-change-the-main-branch-in-sonarqube/13669/8
            if self.get_value('sonar-analyze-branches') and not self.__is_release_branch():
                sonar_optional_flags += [
                    f"-Dsonar.branch.name={self.get_value('branch')}",
                ]

            # run scan
            sh.sonar_scanner(  # pylint: disable=no-member
                f'-Dproject.settings={properties_file}',
                f"-Dsonar.host.url={self.get_value('url')}",
                f"-Dsonar.projectVersion={self.get_value('version')}",
                f'-Dsonar.projectKey={project_key}',
                f'-Dsonar.working.directory={working_directory}',
                *sonar_optional_flags,
                _env={
                    "SONAR_SCANNER_OPTS": \
                        f"-Djavax.net.ssl.trustStore={self.get_value('java-truststore')}"
                },
                _out=sys.stdout,
                _err=sys.stderr
            )
            sonarqube_success = True
        except sh.ErrorReturnCode_1 as error: # pylint: disable=no-member
            # Error Code 1: INTERNAL_ERROR
            # See error codes: https://github.com/SonarSource/sonar-scanner-cli/blob/master/src/main/java/org/sonarsource/scanner/cli/Exit.java # pylint: disable=line-too-long
            step_result.success = False
            step_result.message = "Error running static code analysis" \
                f" using sonar-scanner: {error}"
        except sh.ErrorReturnCode_2: # pylint: disable=no-member
            # Error Code 2: USER_ERROR
            # See error codes: https://github.com/SonarSource/sonar-scanner-cli/blob/master/src/main/java/org/sonarsource/scanner/cli/Exit.java # pylint: disable=line-too-long
            step_result.success = False
            step_result.message = "Static code analysis failed." \
                " See 'sonarqube-result-set' result artifact for details."
        except sh.ErrorReturnCode as error: # pylint: disable=no-member
            # Error Code Other: unexpected
            # See error codes: https://github.com/SonarSource/sonar-scanner-cli/blob/master/src/main/java/org/sonarsource/scanner/cli/Exit.java # pylint: disable=line-too-long
            step_result.success = False
            step_result.message = "Unexpected error running static code analysis" \
                f" using sonar-scanner: {error}"

        step_result.add_artifact(
            name='sonarqube-result-set',
            value=f'{working_directory}/report-task.txt'
        )

        step_result.add_evidence(
            name='sonarqube-quality-gate-pass',
            value=sonarqube_success
        )

        return step_result
    def _run_step(self):
        """Runs the TSSC step implemented by this StepImplementer.

        Returns
        -------
        dict
            Results of running this step.
        """

        # Optional: user and password
        user = ''
        password = ''
        if self.has_config_value(AUTHENTICATION_CONFIG):
            if (self.get_config_value('user')
                    and self.get_config_value('password')):
                user = self.get_config_value('user')
                password = self.get_config_value('password')

        # Required: Get the generate-metadata.version
        if (self.get_step_results('generate-metadata')
                and self.get_step_results('generate-metadata').get('version')):
            version = self.get_step_results('generate-metadata')['version']
        else:
            raise ValueError(
                'Severe error: Generate-metadata results is missing a version tag'
            )

        # Required: properties and exists
        properties_file = self.get_config_value('properties')
        if not properties_file or not os.path.exists(properties_file):
            raise ValueError('Properties file in tssc config not found: ' +
                             properties_file)

        try:
            # Hint:  Call sonar-scanner with sh.sonar_scanner
            #    https://amoffat.github.io/sh/sections/faq.html
            working_directory = self.create_working_folder()
            if user == '':
                sh.sonar_scanner(  # pylint: disable=no-member
                    '-Dproject.settings=' + self.get_config_value('properties'),
                    '-Dsonar.host.url=' + self.get_config_value('url'),
                    '-Dsonar.projectVersion=' + version,
                    '-Dsonar.projectKey=' + \
                        self.get_config_value('application-name') + \
                        ':' + \
                        self.get_config_value('service-name'),
                    '-Dsonar.working.directory=' + working_directory,
                    _out=sys.stdout,
                    _err=sys.stderr
                )
            else:
                sh.sonar_scanner(  # pylint: disable=no-member
                    '-Dproject.settings=' + self.get_config_value('properties'),
                    '-Dsonar.host.url=' + self.get_config_value('url'),
                    '-Dsonar.projectVersion=' + version,
                    '-Dsonar.projectKey=' + \
                        self.get_config_value('application-name') + \
                        ':' + \
                        self.get_config_value('service-name'),
                    '-Dsonar.login='******'-Dsonar.password='******'-Dsonar.working.directory=' + working_directory,
                    _out=sys.stdout,
                    _err=sys.stderr
                )

        except sh.ErrorReturnCode as error:  # pylint: disable=undefined-variable
            raise RuntimeError('Error invoking sonarscanner: {all}'.format(
                all=error)) from error

        results = {
            'result': {
                'success': True,
                'message': 'sonarqube step completed - see report-artifacts',
            },
            'report-artifacts': [{
                'name':
                'sonarqube result set',
                'path':
                f'file://{working_directory}/report-task.txt'
            }]
        }
        return results
    def _run_step(self):
        """Runs the step implemented by this StepImplementer.

        Returns
        -------
        StepResult
            Object containing the dictionary results of this step.
        """
        step_result = StepResult.from_step_implementer(self)

        # Optional: username and password
        username = None
        password = None
        if self.has_config_value(AUTHENTICATION_CONFIG):
            if (self.get_value('username') and self.get_value('password')):
                username = self.get_value('username')
                password = self.get_value('password')

        application_name = self.get_value('application-name')
        service_name = self.get_value('service-name')
        project_key = f'{application_name}:{service_name}'
        url = self.get_value('url')
        version = self.get_value('version')
        properties_file = self.get_value('properties')
        java_truststore = self.get_value('java-truststore')

        if not os.path.exists(properties_file):
            step_result.success = False
            step_result.message = f'Properties file not found: {properties_file}'
            return step_result

        try:
            # Hint:  Call sonar-scanner with sh.sonar_scanner
            #    https://amoffat.github.io/sh/sections/faq.html
            working_directory = self.work_dir_path
            if username:
                sh.sonar_scanner(  # pylint: disable=no-member
                    f'-Dproject.settings={properties_file}',
                    f'-Dsonar.host.url={url}',
                    f'-Dsonar.projectVersion={version}',
                    f'-Dsonar.projectKey={project_key}',
                    f'-Dsonar.login={username}',
                    f'-Dsonar.password={password}',
                    f'-Dsonar.working.directory={working_directory}',
                    _env={"SONAR_SCANNER_OPTS": f'-Djavax.net.ssl.trustStore={java_truststore}'},
                    _out=sys.stdout,
                    _err=sys.stderr
                )
            else:
                sh.sonar_scanner(  # pylint: disable=no-member
                    f'-Dproject.settings={properties_file}',
                    f'-Dsonar.host.url={url}',
                    f'-Dsonar.projectVersion={version}',
                    f'-Dsonar.projectKey={project_key}',
                    f'-Dsonar.working.directory={working_directory}',
                    _env={"SONAR_SCANNER_OPTS": f'-Djavax.net.ssl.trustStore={java_truststore}'},
                    _out=sys.stdout,
                    _err=sys.stderr
                )
        except sh.ErrorReturnCode_1 as error:  # pylint: disable=no-member
            # Error Code 1: INTERNAL_ERROR
            # See error codes: https://github.com/SonarSource/sonar-scanner-cli/blob/master/src/main/java/org/sonarsource/scanner/cli/Exit.java # pylint: disable=line-too-long
            step_result.success = False
            step_result.message = "Error running static code analysis" \
                f" using sonar-scanner: {error}"
        except sh.ErrorReturnCode_2 as error:  # pylint: disable=no-member
            # Error Code 2: USER_ERROR
            # See error codes: https://github.com/SonarSource/sonar-scanner-cli/blob/master/src/main/java/org/sonarsource/scanner/cli/Exit.java # pylint: disable=line-too-long
            step_result.success = False
            step_result.message = "Static code analysis failed." \
                " See 'sonarqube-result-set' result artifact for details."
        except sh.ErrorReturnCode as error:  # pylint: disable=no-member
            # Error Code Other: unexpected
            # See error codes: https://github.com/SonarSource/sonar-scanner-cli/blob/master/src/main/java/org/sonarsource/scanner/cli/Exit.java # pylint: disable=line-too-long
            step_result.success = False
            step_result.message = "Unexpected error running static code analysis" \
                f" using sonar-scanner: {error}"

        step_result.add_artifact(name='sonarqube-result-set',
                                 value=f'{working_directory}/report-task.txt')
        return step_result