Displaying code quality control status to developers in SonarQube

SonarQube is an open platform for continuous code quality control, supporting a wide range of programming languages and providing reports on metrics such as code duplication, adherence to coding standards, test coverage, code complexity, potential bugs, etc. SonarQube visualizes analysis results effectively and allows tracking the project's development dynamics over time.

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

There are two ways to solve this:

  • Run a script to check the code quality control status in SonarQube. If the code quality control in SonarQube fails, then fail the build.
  • Display the code quality control status on the project's main page.

Installing SonarQube

To install SonarQube from RPM packages, we will use the repository https://harbottle.gitlab.io/harbottle-main.

Let's 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

Now we install SonarQube itself.

yum install -y sonarqube

Most plugins will be installed during the installation, but we need to install findbugs and pmd additionally

yum install -y sonarqube-findbugs sonarqube-pmd

Start the service and add it to the autostart

systemctl start sonarqube
systemctl enable sonarqube

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

sonar.web.javaOpts=other parameters -Djava.security.egd=file:/dev/urandom

Running the script to check the code quality control status in SonarQube.

Unfortunately, the sonar-break-maven-plugin has not been updated for a long time. Therefore, we will write our own script.

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

Import into 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 login
  PASSWORD: "admin" # SonarQube password

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...ANALYZING 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 FAILED";
          exit 1 # breaks the build for failure in Step2
      fi
  tags:
    - docker

The .gitlab-ci.yml file is not perfect. It was tested to see if the SonarQube checks completed with the status: "SUCCESS". So far, there have been no other statuses. Once other statuses appear, I will update the .gitlab-ci.yml in this post.

Displaying the quality control status of the source code on the project’s main page

Installing the plugin for SonarQube

yum install -y sonarqube-qualinsight-badges

Log in to SonarQube at the address http://172.26.9.115:9000/
Create a regular user, for example, "badges".
Log in under this user in SonarQube.

Displaying code quality control status to developers in SonarQube

Go to "My account", create a new token, for example named "read_all_repository" and click "Generate".

Displaying code quality control status to developers in SonarQube

You will see that the token has appeared. It will only appear once.

Log in as an administrator.

Go to Configuration -> SVG Badges

Displaying code quality control status to developers in SonarQube

Copy this token into the "Activity badge token" field and click the save button.

Displaying code quality control status to developers in SonarQube

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

For the user badges, you need to check the "Browse" option.

Testing.

For example, let's take a project https://github.com/jitpack/maven-simple.

We import this project.

We add the file .gitlab-ci.yml 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 login
  PASSWORD: "admin" # sonarqube password

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:

Displaying code quality control status to developers in SonarQube

We add badges to README.md and they will look like this:

Displaying code quality control status to developers in SonarQube

The code for displaying badges looks like this:

Displaying code quality control status to developers in SonarQube

Parsing the badge 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.jitpackmaven-simple)
[![Name](http://172.26.9.115:9000/api/badges/gate?key=Project Key)](http://172.26.9.115:9000/dashboard?id=id-project)
[![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.jitpackmaven-simple)
[![Metric Name](http://172.26.9.115:9000/api/badges/measure?key=Project Key&metric=METRIC)](http://172.26.9.115:9000/dashboard?id=id-project)

Where to find/check Project Key and project id.

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

Displaying code quality control status to developers in SonarQube

Options for obtaining metrics can be viewed here.

Please send all pull requests for improvements or bug fixes 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

Buy reliable website hosting with DDoS protection, VPS VDS servers 🔥 Buy reliable website hosting with DDoS protection, VPS VDS servers | ProHoster