Show developers the status of source code quality control in SonarQube

SonarQube is an open source code continuous quality assurance platform that supports a large number of programming languages ​​and provides reporting on metrics such as code duplication, coding standards compliance, test coverage, code complexity, potential bugs, and more. SonarQube conveniently visualizes the results of the analysis and allows you to track the dynamics of the project development over time.

Objective: Show developers the quality control status of source code in SonarQube.

There are two ways to solve:

  • Run script to check source code quality control status in SonarQube. If the quality control of the source code in SonarQube fails, then fail the build.
  • Show source code quality control status on the main project page.

Installing SonarQube

To install sonarqube from rpm packages, use the repository https://harbottle.gitlab.io/harbottle-main.

Install the package with the repository for CentOS 7.

yum install -y https://harbottle.gitlab.io/harbottle-main/7/x86_64/harbottle-main-release.rpm

Installing sonarqube itself.

yum install -y sonarqube

During installation, most plugins will be installed, but you need to install findbugs and pmd

yum install -y sonarqube-findbugs sonarqube-pmd

We start the service and add it to startup

systemctl start sonarqube
systemctl enable sonarqube

If it takes a long time to load, then add a random number generator /dev/./urandom to the end of the sonar.web.javaOpts options

sonar.web.javaOpts=Π΄Ρ€ΡƒΠ³ΠΈΠ΅ ΠΏΠ°Ρ€Π°ΠΌΠ΅Ρ‚Ρ€Ρ‹ -Djava.security.egd=file:/dev/urandom

Run script to check source code quality control status in SonarQube.

Unfortunately, sonar-break-maven-plugin has not been updated for a long time. So let's write our own script.

For testing, we will use the repository https://github.com/uweplonus/spotbugs-examples.

Import to Gitlab. Add the .gitlab-ci.yml file:

variables:
  MAVEN_OPTS: "-Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=~/.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
  MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"
  SONAR_HOST_URL: "http://172.26.9.226:9000"
  LOGIN: "admin" # Π»ΠΎΠ³ΠΈΠ½ sonarqube
  PASSWORD: "admin" # ΠΏΠ°Ρ€ΠΎΠ»ΡŒ sonarqube

cache:
  paths:
    - .m2/repository

build:
  image: maven:3.3.9-jdk-8
  stage: build
  script:
    - apt install -y jq || true
    - mvn $MAVEN_CLI_OPTS -Dmaven.test.failure.ignore=true org.jacoco:jacoco-maven-plugin:0.8.5:prepare-agent clean verify org.jacoco:jacoco-maven-plugin:0.8.5:report
    - mvn $MAVEN_CLI_OPTS -Dmaven.test.skip=true verify sonar:sonar -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$LOGIN -Dsonar.password=$PASSWORD -Dsonar.gitlab.project_id=$CI_PROJECT_PATH -Dsonar.gitlab.commit_sha=$CI_COMMIT_SHA -Dsonar.gitlab.ref_name=$CI_COMMIT_REF_NAME
    - export URL=$(cat target/sonar/report-task.txt | grep ceTaskUrl | cut -c11- ) #URL where report gets stored
    - echo $URL
    - |
      while : ;do
          curl -k -u "$LOGIN":"$PASSWORD" "$URL" -o analysis.txt
          export status=$(cat analysis.txt | jq -r '.task.status') #Status as SUCCESS, CANCELED, IN_PROGRESS or FAILED
          echo $status
          if [ ${status} == "SUCCESS" ];then
            echo "SONAR ANALYSIS SUCCESS";
            break
          fi
          sleep 5
      done
    - curl -k -u "$LOGIN":"$PASSWORD" "$URL" -o analysis.txt
    - export status=$(cat analysis.txt | jq -r '.task.status') #Status as SUCCESS, CANCELED or FAILED
    - export analysisId=$(cat analysis.txt | jq -r '.task.analysisId') #Get the analysis Id
    - |
      if [ "$status" == "SUCCESS" ]; then
        echo -e "SONAR ANALYSIS SUCCESSFUL...ANALYSING RESULTS";
        curl -k -u "$LOGIN":"$PASSWORD" "$SONAR_HOST_URL/api/qualitygates/project_status?analysisId=$analysisId" -o result.txt; #Analysis result like critical, major and minor issues
        export result=$(cat result.txt | jq -r '.projectStatus.status');

        if [ "$result" == "ERROR" ];then
          echo -e "91mSONAR RESULTS FAILED";
          echo "$(cat result.txt | jq -r '.projectStatus.conditions')"; #prints the critical, major and minor violations
          exit 1 #breaks the build for violations
        else
          echo -e "SONAR RESULTS SUCCESSFUL";
          echo "$(cat result.txt | jq -r '.projectStatus.conditions')";
          exit 0
        fi
      else
          echo -e "e[91mSONAR ANALYSIS FAILEDe[0m";
          exit 1 #breaks the build for failure in Step2
      fi
  tags:
    - docker

The .gitlab-ci.yml file is not ideal. Tested if check tasks in sonarqube ended with status: "SUCCESS". So far, there have been no other statuses. As there will be other statuses, I will correct .gitlab-ci.yml in this post.

Display on the main page of the project the status of quality control of the source code

Installing the plugin for SonarQube

yum install -y sonarqube-qualinsight-badges

We go to SonarQube at http://172.26.9.115:9000/
We create a normal user, for example "badges".
We go under this user in SonarQube.

Show developers the status of source code quality control in SonarQube

We go to "My account", create a new token, for example with the name "read_all_repository" and click "Generate".

Show developers the status of source code quality control in SonarQube

We see that a token has appeared. It only appears once.

We go under the administrator.

Go to Configuration -> SVG Badges

Show developers the status of source code quality control in SonarQube

Copy this token to the "Activity badge token" field and press the save button.

Show developers the status of source code quality control in SonarQube

Go to Administration -> Security -> Permission Templates -> Default template (and other templates that you will have).

The badges user must check the "Browse" checkbox.

Testing.

Let's take the project as an example. https://github.com/jitpack/maven-simple.

Let's import this project.

We add the .gitlab-ci.yml file to the root of the project with the following content.

variables:
  MAVEN_OPTS: "-Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=~/.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true"
  MAVEN_CLI_OPTS: "--batch-mode --errors --fail-at-end --show-version -DinstallAtEnd=true -DdeployAtEnd=true"
  SONAR_HOST_URL: "http://172.26.9.115:9000"
  LOGIN: "admin" # Π»ΠΎΠ³ΠΈΠ½ sonarqube
  PASSWORD: "admin" # ΠΏΠ°Ρ€ΠΎΠ»ΡŒ sonarqube

cache:
  paths:
    - .m2/repository

build:
  image: maven:3.3.9-jdk-8
  stage: build
  script:
    - mvn $MAVEN_CLI_OPTS -Dmaven.test.failure.ignore=true org.jacoco:jacoco-maven-plugin:0.8.5:prepare-agent clean verify org.jacoco:jacoco-maven-plugin:0.8.5:report
    - mvn $MAVEN_CLI_OPTS -Dmaven.test.skip=true verify sonar:sonar -Dsonar.host.url=$SONAR_HOST_URL -Dsonar.login=$LOGIN -Dsonar.password=$PASSWORD -Dsonar.gitlab.project_id=$CI_PROJECT_PATH -Dsonar.gitlab.commit_sha=$CI_COMMIT_SHA -Dsonar.gitlab.ref_name=$CI_COMMIT_REF_NAME
  tags:
    - docker

In SonarQube, the project will look like this:

Show developers the status of source code quality control in SonarQube

Add bages to README.md and they will look like this:

Show developers the status of source code quality control in SonarQube

The code for displaying badges looks like this:

Show developers the status of source code quality control in SonarQube

Parsing the badges display string:

[![Quality Gate](http://172.26.9.115:9000/api/badges/gate?key=com.github.jitpack:maven-simple)](http://172.26.9.115:9000/dashboard?id=com.github.jitpack%3Amaven-simple)
[![НазваниС](http://172.26.9.115:9000/api/badges/gate?key=Project Key)](http://172.26.9.115:9000/dashboard?id=id-ΠΏΡ€ΠΎΠ΅ΠΊΡ‚Π°)
[![Coverage](http://172.26.9.115:9000/api/badges/measure?key=com.github.jitpack:maven-simple&metric=coverage)](http://172.26.9.115:9000/dashboard?id=com.github.jitpack%3Amaven-simple)
[![НазваниС ΠœΠ΅Ρ‚Ρ€ΠΈΠΊΠΈ](http://172.26.9.115:9000/api/badges/measure?key=Project Key&metric=ΠœΠ•Π’Π Π˜ΠšΠ)](http://172.26.9.115:9000/dashboard?id=id-ΠΏΡ€ΠΎΠ΅ΠΊΡ‚Π°)

Where to get/check Project Key and project id.

The Project Key is on the bottom right. The URL contains the project id.

Show developers the status of source code quality control in SonarQube

Options for getting metrics can be see here.

All pull requests for improvement, bug fixes submit to this repository.

Telegram chat about SonarQube https://t.me/sonarqube_ru
Telegram chat about DevSecOps - secure DevOps https://t.me/sec_devops

Source: habr.com

Add a comment